<div id="foo"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.className += " bar";
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.setAttribute("class", "bar");
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.add("bar");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
setAttribute | |
classList |
Test name | Executions per second |
---|---|
className | 2.2 Ops/sec |
setAttribute | 7884.0 Ops/sec |
classList | 4226.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Definition
The benchmark defines three test cases:
className
: This test case checks how long it takes to add a class name to an element using the className
property.setAttribute
: This test case checks how long it takes to set an attribute on an element with the value "class" and the value "bar".classList
: This test case checks how long it takes to add an element to the class list of an element.Options compared
The benchmark is comparing three different approaches:
className
property to add a class name.setAttribute
method to set an attribute on the element.classList
API to add an element to the class list.Pros and Cons of each approach
Here's a brief overview of the pros and cons of each approach:
className
property, and some browsers may have issues with attribute handling.Library/Additional features used
None of the test cases use any external libraries or additional JavaScript features beyond what's already included in the benchmark. The classList
API is a native feature that's been added to modern browsers, but it's not enabled by default for older browsers.
Special JS features/syntax
The benchmark does not use any special JavaScript features or syntax beyond what's required for the test cases.
Other alternatives
If you want to run this benchmark on different browsers or platforms, you can modify the Html Preparation Code
and adjust the script preparation code accordingly. Additionally, you could add more test cases to compare other approaches, such as using CSS classes or other attribute manipulation methods.
Keep in mind that running a microbenchmark like this one requires careful consideration of factors like hardware, browser versions, and JavaScript engine optimizations. The results may vary depending on your specific environment and setup.