<div id="foo" class="c1 c2 c3"></div>
var element = document.getElementById("foo");
for(var i = 0; i < 500; i++) {
var z = element.className.split(' ');
z.push(i);
element.className = z.join(' ');
}
var element = document.getElementById("foo");
for(var i = 0; i < 500; i++) {
element.classList.add(i);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
classList |
Test name | Executions per second |
---|---|
className | 2.0 Ops/sec |
classList | 42.2 Ops/sec |
Let's break down the provided benchmark JSON and explain what's being tested.
Benchmark Definition
The benchmark definition is comparing three approaches to update the class
attribute of an HTML element:
className
: Using the split()
method to split the current class names, adding a new class name, and then joining the updated class names back together.getAttribute
: Not shown in the benchmark definition, but presumably using the setAttribute()
method to set the value of the class
attribute.classList
: Using the classList.add()
method to add a new class name to the element's classList
.Options Compared
The two options being compared are:
className
: A manual, string-based approach using the split()
, push()
, and join()
methods.classList
: A DOM-based approach using the classList.add()
method.Pros and Cons of Each Approach
className
:classList
approach.classList
:className
approach.classList
API, which may not be available in older browsers or environments.Other Considerations
The benchmark definition doesn't account for other factors that might affect performance, such as:
Library Used
In this case, none of the options are using a specific library. However, if we were to consider the classList
approach, it's worth noting that the classList
API is a part of the W3C DOM Standard and has been supported by most modern browsers for several years.
Special JS Features or Syntax
None of the options in this benchmark definition rely on any special JavaScript features or syntax. They are all relatively straightforward and easy to understand.
Alternative Approaches
Some alternative approaches to updating the class
attribute might include:
It's worth noting that the classList
approach is generally considered the most efficient and modern way to update class names in HTML elements.