<div id="foo"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.className = "is-active";
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.setAttribute("data-state", "active");
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.add("is-active");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
setAttribute | |
classList |
Test name | Executions per second |
---|---|
className | 68531.7 Ops/sec |
setAttribute | 30763.7 Ops/sec |
classList | 26122.6 Ops/sec |
Overview
The MeasureThat.net benchmark measures the performance of three approaches for setting data attributes or classes on an HTML element: className
, setAttribute
, and classList
. The benchmark is designed to evaluate which approach is the fastest.
Benchmark Definition
The benchmark definition specifies that we have a single HTML element (<div id="foo"></div>
) and perform an operation (setting a class) 1000 times in a loop. The three approaches are:
className
: Setting the className
attribute directly.setAttribute
: Using the setAttribute
method to set the data-state
attribute with a value of "active"
.classList
: Using the classList
property to add the is-active
class.Options Compared
The three options are compared in terms of their performance, measured by the number of executions per second (ExecutionsPerSecond). The option with the highest value is considered the fastest.
Pros and Cons of Each Approach
className
because it avoids string concatenation. However, it requires using the setAttribute
method, which may add overhead due to function call and argument passing.className
since it involves a direct property access and doesn't require string concatenation.Library Used
None, as this is a built-in JavaScript feature.
Special JS Feature or Syntax
The benchmark uses the classList
property, which is a modern JavaScript feature introduced in HTML5. It allows developers to easily manage classes on an element without needing to concatenate strings or use other workarounds.
Other Considerations
data-state
attribute is set in isolation from other attributes. In reality, attribute values can interact with each other and affect performance.Alternatives
Other alternatives to the three options compared include:
style
property: Setting a CSS style directly on the element can be faster than using className
or setAttribute
. However, it requires more code and may not provide the same level of flexibility.In conclusion, while there's no single "best" approach, classList
is likely to be the fastest option due to its direct property access and efficient use of modern JavaScript features.