<div id="foo"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.className = "bar lamp";
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.setAttribute("class", "bar lamp");
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.add("bar");
element.classList.add("lamp");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
setAttribute | |
classList |
Test name | Executions per second |
---|---|
className | 6084.8 Ops/sec |
setAttribute | 3466.6 Ops/sec |
classList | 985.7 Ops/sec |
Let's break down the provided benchmark and its components.
Benchmark Definition
The benchmark measures the performance of three different approaches to add multiple classes to an HTML element:
className
(using the =
operator)setAttribute
(using the setAttribute
method)classList
(using the classList.add
method)Options Compared
These three options are compared because they may have different performance characteristics due to various factors such as parsing, DOM manipulation, and browser implementation.
Pros and Cons of Each Approach:
className
since it only sets a single attribute value.setAttribute
), which might introduce overhead.classList
API in older browsers.Library and Its Purpose
None of the options explicitly use a library or framework in this benchmark.
Special JS Features/Syntax
There are no special JavaScript features or syntax used in these benchmarks, such as async/await, promises, or destructuring.
Other Alternatives
If you were to compare alternative approaches, some possibilities could include:
style
attribute instead of className
However, these alternatives are not explicitly mentioned in the benchmark.
Overall, this benchmark provides a straightforward comparison of three common methods for adding multiple classes to an HTML element, making it easy to understand and reproduce the results.