<div id="foo"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.className = "bar";
}
var element = document.getElementById("foo");
var i = 1000;
var cl = element.classList;
while (i--) {
cl.add("bar");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
classList |
Test name | Executions per second |
---|---|
className | 3529.3 Ops/sec |
classList | 2165.7 Ops/sec |
I'd be happy to explain the benchmark being measured on MeasureThat.net.
The benchmark is comparing two approaches for setting the class name of an HTML element:
className
property: This approach uses the dot notation to set the class name of the element. The syntax element.className = "bar"
sets the class name of the element to "bar"
.classList
property and its methods (add, addAll): This approach uses the classList
property and its methods, such as classList.add("bar")
, to set the class name of the element.Pros and Cons
className
property:
Pros:
Cons:
classList
property and its methods:
Pros:
Cons:
classList
property is supported in modern browsers)Other Considerations
The choice between these two approaches depends on the specific use case and performance requirements. If simplicity and familiarity are more important than raw performance, the dot notation approach might be preferred. However, if speed and explicit class management are critical, the classList
property and its methods are likely a better choice.
Library and Syntax
In this benchmark, the library being used is not explicitly mentioned. However, it's worth noting that the classList
property was introduced in HTML5 (2008) and became widely supported in modern browsers over time. The syntax classList.add("bar")
has been part of the standard since then.
Other Alternatives
If you're interested in exploring alternative approaches or performance optimizations for setting class names, here are a few examples:
.addClass()
).setAttribute()
method with the "class" attribute name).Keep in mind that these alternatives might not offer significant performance gains over the current best approach (using the classList
property and its methods) but can be interesting to explore from a theoretical or optimization perspective.