<div id="foo" class="neki"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.className += " bar bar2 bar3";
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.add("bar");
element.classList.add("bar2");
element.classList.add("bar3");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
classList |
Test name | Executions per second |
---|---|
className | 1.6 Ops/sec |
classList | 1783.3 Ops/sec |
Let's break down the provided JSON data and explain what's being tested.
Benchmark Definition
The benchmark is testing three different approaches to add classes to an HTML element:
className
: Adding a string of class names using the className
property.setAttribute
: Adding multiple attributes (in this case, class names) using the setAttribute
method.classList
(v4): Adding one or more classes to an element using the classList
API.The benchmark is designed to measure which approach performs better in terms of execution speed.
Options Compared
className
: This approach adds multiple class names to the element by concatenating them with a space. However, this can lead to slower performance if the resulting string becomes too large.setAttribute
: This approach adds each attribute individually using setAttribute
. While it's more explicit, it can also be slower due to the overhead of setting individual attributes.classList
(v4): This approach uses a more efficient method for adding classes. The classList.add()
method is optimized to handle multiple additions quickly and efficiently.Pros and Cons
className
:setAttribute
:classList
(v4):classList
API in modern browsers.Library and Purpose
None are explicitly mentioned in the benchmark. However, the classList
API is a built-in browser feature introduced with HTML5.
Special JS Feature or Syntax
The classList
API uses the ES6 class syntax (e.g., classList
) and is supported by most modern browsers. If you're using an older JavaScript version or a non-standard library, you might not have access to this API.
Other Alternatives
If you need alternatives for adding classes to an element:
setAttribute
: You can use the setAttribute
method with the class
attribute explicitly.innerHTML
: Adding multiple class names using innerHTML
is generally slower than other methods.style
attribute: Setting the style
attribute with multiple class names can be slower due to CSS parsing overhead.Keep in mind that these alternatives might not provide the same level of performance as the classList
API, which is optimized for modern browsers.