<div id="foo" class="test"></div>
var element = document.getElementById("foo");
element.className = "foo";
var i = 1000;
while (i--) {
element.className += " bar";
}
var element = document.getElementById("foo");
element.className = "foo";
var i = 1000;
while (i--) {
element.classList.add("bar");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Test123 | |
Test4455 |
Test name | Executions per second |
---|---|
Test123 | 33.3 Ops/sec |
Test4455 | 2176.0 Ops/sec |
Let's break down the benchmark and analyze what's being tested, compared, and the pros/cons of each approach.
Benchmark Overview
The benchmark measures the performance difference between two approaches:
className
property (Test123)classList.add()
method (Test4455)Script Preparation Code
The script preparation code is empty, which means that the benchmarker doesn't need to set up any external dependencies or initialize any libraries.
HTML Preparation Code
The HTML preparation code creates an HTML element with an ID of "foo" and assigns a class of "test". This element will be used as a target for both tests.
Individual Test Cases
There are two test cases:
element.className = "foo";
and then appends a new class "bar" in a loop (while (i--) { ... }
). This approach uses the className
property to dynamically set classes on the element.element.classList.add("bar");
in a loop (while (i--) { ... }
). This approach uses the classList
API to add and remove classes.Comparison
The benchmark is comparing the performance of these two approaches:
className
property, while Test4455 uses the classList.add()
method.Pros and Cons
classList
API.Other Considerations
The benchmark doesn't account for other factors that might affect performance, such as:
Library or Framework Used (if applicable)
There are no apparent libraries or frameworks used in the benchmark. The tests only use standard JavaScript features.
No special JS feature or syntax is used beyond the classList
API, which is a modern addition to the ECMAScript specification.
Alternatives
If you wanted to create similar benchmarks, you could explore other approaches for adding CSS classes, such as:
style
attribute and setting multiple values with spaces separated (e.g., "class": "foo bar baz"
).lodash
or underscore
.Keep in mind that the performance differences between these approaches may vary depending on the specific use case and browser implementations.