<div id="test" class="first">Testing</div>
var el = document.getElementById('test');
el.classList.add("second");
el.setAttribute("class", el.className + " second");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
classList.add | |
setAttribute |
Test name | Executions per second |
---|---|
classList.add | 4131483.2 Ops/sec |
setAttribute | 2752.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The benchmark compares two approaches for adding an attribute (or class) to an HTML element: using classList.add()
and using setAttribute()
. The test case is designed to measure the performance difference between these two methods, which are commonly used in JavaScript development.
Options Compared
Two options are compared:
classList.add()
: This method adds a class (i.e., attribute) to an element's class list. It's a modern and concise way to modify an element's classes.setAttribute()
: This method sets the value of a named attribute on an element. In this case, it's used to add a new class to an element.Pros and Cons
classList.add()
:
Pros:
classList
since 2015)Cons:
setAttribute()
due to the overhead of manipulating a class listsetAttribute()
:
Pros:
Cons:
Other Considerations
When deciding between classList.add()
and setAttribute()
, consider the following factors:
setAttribute()
might be a better choice.classList.add()
for more concise and readable code.classList.add()
is faster than setAttribute()
, but the difference may not be noticeable in all scenarios.Libraries and Special Features
In this benchmark, there are no libraries used. However, it's worth noting that some JavaScript frameworks or libraries (e.g., React) might have their own classes for managing class names, which could affect the performance of classList.add()
and setAttribute()
.
As for special JS features or syntax, there is none mentioned in this benchmark definition.
Alternatives
If you're interested in exploring alternative approaches to adding attributes or classes to elements, consider:
DOM Triton
: A web standards library that provides a more modern and efficient way of manipulating the DOM.fast-class-list
: A lightweight library for managing class lists, which can be used with classList.add()
for improved performance.These alternatives might offer better performance or features than classList.add()
, but their adoption is still limited compared to the standard classList
API.