<div id="foo" class="a b c"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
var classes = (0 == i % 2) ? "1 2 3" : "4 5 6";
element.setAttribute("class", classes);
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
var classes = (0 == i % 2) ? "1 2 3" : "4 5 6";
element.className = classes;
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
var classes = (0 == i % 2) ? ["1", "2", "3"] : ["4", "5", "6"];
element.classList.remove(element.classList);
element.classList.add(classes);
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
var classes = (0 == i % 2) ? ["1", "2", "3"] : ["4", "5", "6"];
element.setAttribute("class", classes.join(' '));
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
var classes = (0 == i % 2) ? ["1", "2", "3"] : ["4", "5", "6"];
element.className = classes.join(' ');
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
setAttribute | |
className | |
classList | |
setAttribte=List | |
className=List |
Test name | Executions per second |
---|---|
setAttribute | 3831.8 Ops/sec |
className | 4448.7 Ops/sec |
classList | 679.6 Ops/sec |
setAttribte=List | 2880.0 Ops/sec |
className=List | 3150.9 Ops/sec |
Let's break down what's being tested and analyzed in this benchmark.
What is being compared?
The benchmark compares five different approaches to set multiple CSS classes on an HTML element:
setAttribute
methodclassName
propertyclassList
API (with add()
and remove()
methods)setAttribute
method with a list of classes joined by spaces (setAttribte=List
)className
property with a list of classes joined by spaces (className=List
)What is being tested?
The test case creates an HTML element with the ID "foo" and sets multiple CSS classes on it using each of the five approaches, iterating 1000 times to simulate a large number of executions. The goal is to measure which approach performs best in terms of execution speed.
Pros and cons of each approach:
setAttribute
, but with a list of classes joined by spaces; Cons: may be slower than className
or classList
.Library and special JS features:
No external libraries are used in this benchmark. However, the test case does utilize some modern JavaScript features:
...
operator (spread syntax) is used in the classList
approach to pass a list of classes as arguments.[ ]
notation (array literal) is used to create an array of class names.Other considerations:
Alternatives:
Other approaches to set multiple CSS classes on an HTML element include:
setAttribute
.Keep in mind that these alternatives may have their own performance implications and trade-offs, which should be carefully considered when choosing an approach.