<div id="foo"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.add("bar");
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.toggle("bar");
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.setAttribute('active', true);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
classList add | |
classList toggle | |
setAttribute |
Test name | Executions per second |
---|---|
classList add | 3331.1 Ops/sec |
classList toggle | 3394.8 Ops/sec |
setAttribute | 2200.1 Ops/sec |
Let's break down what's being tested in the provided benchmark.
The benchmark compares three approaches to modify an HTML element's class list:
classList.add()
(adding a class)classList.toggle()
(toggling a class)setAttribute('active', true)
(setting a custom attribute)Options compared:
classList
property.Pros and Cons of each approach:
classList.add()
:classList.toggle()
:classList.add()
, but also allows for removing classes by passing the class name with no argument (e.g., element.classList.toggle('bar')
). This method is also efficient and easy to read.classList.add()
is that it toggles the presence of a class, which can be misleading if not used carefully.setAttribute('active', true)
:classList.add()
or classList.toggle()
, making it less suitable for performance-critical code.Library and purpose:
There is no explicit library mentioned in the benchmark definition. However, it's worth noting that classList
is a part of the HTML5 DOM API, which has been widely adopted by modern browsers.
Special JS feature or syntax:
None are explicitly mentioned in this benchmark.
Other considerations:
When choosing between these methods, consider factors like:
setAttribute()
might be a better choice.classList.add()
and classList.toggle()
are likely to be faster due to their native implementation.Alternatives:
If you need to support even older browsers or have specific requirements not covered by this benchmark, consider using other methods:
element.className += 'bar';
.element.className = element.className.replace(' bar', '');
(note the space at the end of the class name).element.setAttribute('custom-attribute', 'value');
.Keep in mind that these alternatives might have different performance characteristics and may not be as efficient as the methods tested in this benchmark.