addFunction vs classList

4 years ago
User agent: Mozilla/5.0 (Windows NT 10.0; WOW64; Trident/7.0; rv:11.0) like Gecko
Test name Executions per second
addClass function 426.4 Ops/sec
classList 2794.9 Ops/sec
HTML Preparation code:
AخA
 
1
<div id="foo"></div>
Script Preparation code:
 
function addClass(el, classNames)
{
  if (!classNames) { return; }
 
        if (!Object.prototype.toString.call(classNames) === "[object Array]")
        {
            classNames = classNames.split(' ');
        }
        var className = el.getAttribute("class") || "";
 
        var i, classMap = {}, currentClasses = [], length;
 
        if (className !== null)
        {
            currentClasses = className.split(" ");
 
            length = currentClasses.length;
            for (i = 0; i < length; i++)
            {
                if (currentClasses[i] !== "")
                {
                    classMap[currentClasses[i]] = "";
                }
            }
        }
 
        var changed = false, trimmedName;
        var newAdded = [];
        length = classNames.length;
        for (i = 0; i < length; i++)
        {
            trimmedName = classNames[i].trim();
            if ((trimmedName.length > 0) && !(trimmedName in classMap))
            {
                currentClasses.push(trimmedName);
                newAdded.push(trimmedName);
                classMap[trimmedName] = "";
                changed = true;
            }
        }
 
        if (changed)
        {
            el.setAttribute("class", currentClasses.join(" ").trim());
        }
 
        return newAdded;
}
Tests:
  • addClass function

     
    var element = document.getElementById("foo");
    var i = 1000;
    while (i--) {
        addClass(element, "bar");
    }
  • classList

     
    var element = document.getElementById("foo");
    var i = 1000;
    while (i--) {
        element.classList.add("bar");
    }
Open this result on MeasureThat.net