<div id="foo"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.className = "bar bar1 bar2 bar3 bar4";
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.add("bar");
element.classList.add("bar1");
element.classList.add("bar2");
element.classList.add("bar3");
element.classList.add("bar4");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
classList |
Test name | Executions per second |
---|---|
className | 3385.7 Ops/sec |
classList | 925.2 Ops/sec |
Let's break down what is being tested in the provided benchmark.
The benchmark compares three approaches to adding classes to an HTML element:
className
: This approach sets the entire class name of the element as a single string, e.g., "bar bar1 bar2 bar3 bar4"
. This is done using the assignment operator (=
).setAttribute
: This approach uses the setAttribute
method to set individual class names one by one, e.g., element.setAttribute('class', 'bar');
, element.setAttribute('class', 'bar1');
, and so on.classList
: This approach uses the classList
property of the element to add multiple classes at once, e.g., element.classList.add('bar');
, element.classList.add('bar1');
, and so on.Pros and Cons:
setAttribute
: This approach is generally slower than using the classList
property, as each individual setAttribute call incurs additional overhead. However, it can still be faster for small sets of classes.classList
: This approach is usually the fastest, as it uses a optimized internal data structure to store and manage the class names.Other Considerations:
classList
property is a relatively new feature in JavaScript (introduced in ECMAScript 2015), and its implementation may vary across different browsers.Library/Features Used:
None are explicitly mentioned in the benchmark definition, but some assumptions can be made:
document.getElementById
method is used to retrieve an element by its ID.Element
object has a className
property, setAttribute
method, and classList
property.If you're using modern JavaScript versions, the classList
property is supported natively in most browsers. If not, you may need to polyfill or use a third-party library to achieve similar behavior.
Alternative Approaches:
Other approaches to adding classes to an element could include:
addRule
method of the CSSStyleSheet
object).