<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;
var cl = element.classList;
while (i--) {
cl.add("bar");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
classList |
Test name | Executions per second |
---|---|
className | 2.0 Ops/sec |
classList | 2449.6 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares two approaches for adding classes to an HTML element: using className
or using the classList
property.
Script Preparation Code and Html Preparation Code
The script preparation code is empty, which means that the test cases will use a pre-existing JavaScript environment. The html preparation code creates a simple HTML element with an ID of "foo".
Individual Test Cases
There are two test cases:
while
loop to add the string "bar " repeatedly to the className
property of the element
. The loop iterates 1000 times, which is likely intended to be a high number to stress the JavaScript engine.classList
property of the element
, but uses the add()
method instead of concatenating strings.Library and Special JS Features
There are no libraries mentioned in this benchmark, and it does not use any special JavaScript features such as let
or const
. The only notable thing is that the test case for classList
uses the add()
method, which was introduced in ECMAScript 2017 (ES7).
Pros and Cons of Each Approach
while
loop may cause unexpected behavior if the browser's JavaScript engine is not optimized for infinite loops.add()
method is designed for efficient class addition and removal.Other Alternatives
If you wanted to add classes to an HTML element in JavaScript, there are other alternatives:
document.body.classList.add()
: This would add the string "bar" as a single class name to the element's classList
. While this is not exactly what the benchmark tests, it could be used as an alternative.element.className += 'bar '
;**: This would concatenate the string "bar " to the existing
className`, which could potentially lead to performance issues due to string creation and garbage collection.Benchmark Results
The benchmark results show that the test case for classList
outperforms the one for className
. This is expected, given the advantages of using the add()
method.