<div id='foo'></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList = "bar";
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.className = "bar";
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
classList | |
className |
Test name | Executions per second |
---|---|
classList | 1842.3 Ops/sec |
className | 5810.5 Ops/sec |
Let's break down the benchmark and its test cases to understand what's being measured.
Benchmark Definition
The benchmark is defined by a JSON object with the following properties:
Name
: A human-readable name for the benchmark, which in this case is "className vs classList with =".Description
: An optional description of the benchmark, which is empty in this case.Script Preparation Code
: An optional script that should be executed before running the benchmark, which is also empty in this case.Html Preparation Code
: The HTML code that sets up the environment for the benchmark. In this case, a simple <div>
element with an ID of "foo" is created.Individual Test Cases
The benchmark consists of two individual test cases:
classList
to set the value of the class
attribute of the HTML element.while
loop iterates 1000 times, and in each iteration, it sets the class
attribute using classList
.className
to set the value of the class
attribute of the HTML element.while
loop iterates 1000 times, and in each iteration, it sets the class
attribute using className
.Library Usage
In both test cases, no explicit libraries are used. However, it's worth noting that the classList
property is a part of the HTML5 specification, which means that modern browsers support it by default.
Special JS Features or Syntax
Neither of the two test cases uses any special JavaScript features or syntax beyond what's already covered in the ECMAScript standard.
Pros and Cons of Different Approaches
The main difference between classList
and className
is how they interact with browser rendering. When using classList
, browsers can optimize the attribute updates by only re-rendering elements that have changes to their class list. This can lead to better performance, especially when dealing with complex class hierarchies.
On the other hand, using className
requires the browser to update the entire class list for each element every time it's modified. While this might seem like a straightforward approach, it can be slower because browsers need to re-render all elements that have changed classes.
Other Alternatives
If you were to implement these benchmarks yourself, you could also consider using other approaches, such as:
getAttribute
and setAttribute
instead of classList
or className
.addClassClass
method.Keep in mind that these alternative approaches might change the execution time or behavior of your benchmark, so it's essential to carefully design and test them before publishing results.