<div id="foo" class="lorem"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.className += " bar";
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.add("bar");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
classList |
Test name | Executions per second |
---|---|
className | 2.4 Ops/sec |
classList | 3663.2 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark is comparing three approaches to adding a class to an HTML element:
className
property (adding a string to the existing class names)setAttribute
method (setting an attribute with a specific value, in this case, a class name)classList
API (adding a class using the add
method)Options Compared
The benchmark is comparing two options for each approach:
className
: Using the +=
operator to concatenate a new class name to the existing classes.setAttribute
: Setting an attribute with a specific value, in this case, a class name.Pros and Cons of Each Approach
className:
setAttribute:
className
, as it allows setting any attribute value, not just a class name.className
property, which can lead to performance issues due to attribute lookup and parsing overhead.classList:
className
or setAttribute
, although it's getting more common with each passing year.Library Usage
None of the benchmark test cases use a library, but they do rely on the following APIs:
document.getElementById
: Used to retrieve an HTML element by its ID.Element.className
and Element.classList
: The property and API used to manipulate class names.Special JS Features or Syntax
There are no special JavaScript features or syntax being tested in this benchmark. It's focused on comparing the performance of three simple approaches to adding classes to an HTML element.
Other Alternatives
If you're interested in exploring alternative approaches, consider these:
Keep in mind that these alternatives might introduce additional overhead, dependencies, or complexity to your project. The benchmark's simplicity and focus on basic class manipulation make it an excellent starting point for exploring performance optimizations in this context.