<div id="foo" class="some other classname"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.className += " bar";
element.className = element.className.slice(0, -4);
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
var items = element.className.split(' ')
if (items.indexOf('bar') < 0) {
items.push('bar');
element.className = items.join(' ')
}
items = element.className.split(' ')
items.pop()
element.className = items.join(' ');
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.add("bar");
element.classList.remove("bar");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
string | |
array | |
classList |
Test name | Executions per second |
---|---|
string | 246.9 Ops/sec |
array | 218.0 Ops/sec |
classList | 170.7 Ops/sec |
I'll break down the benchmark and explain what's being tested.
Benchmark Overview
The test measures the performance of three different approaches to toggle a class name on an HTML element:
classList
property to add or remove the "bar" class from the element.Options Compared
The three options are compared in terms of their performance (number of executions per second). The benchmark is run on an IE 11 browser and Windows desktop platform.
Pros and Cons of Each Approach
Libraries and Special JS Features
None of the test cases use any libraries or special JavaScript features beyond the standard DOM API.
Other Considerations
When choosing between these approaches, consider the following:
classList
API is likely the best option due to its native implementation.Alternatives
If you're interested in exploring alternative approaches, consider:
Keep in mind that these alternatives may have trade-offs in terms of performance, memory usage, or ease of implementation.