<div id="test" class="first">Testing</div>
var el = document.getElementById('test');
el.classList.add("second");
el.setAttribute("class", el.getAttribute("class") + " second");
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
classList.add | |
setAttribute |
Test name | Executions per second |
---|---|
classList.add | 8051140.5 Ops/sec |
setAttribute | 2313.2 Ops/sec |
Let's break down what's being tested on the provided JSON.
Benchmark Definition
The benchmark is comparing two approaches to adding an attribute (class in this case) to an HTML element using JavaScript:
classList.add()
: This method is part of the DOM API, which provides a convenient way to manage classes on an element.setAttribute()
: This method is used to set the value of an attribute on an element.Options Compared
The benchmark is comparing these two approaches in terms of performance.
Pros and Cons
classList.add()
:setAttribute()
:Library Used
The classList
property is part of the DOM API, which is a standard library in modern browsers. The purpose of classList.add()
is to add a class to an element and update its classes list accordingly.
Special JavaScript Feature/Syntax
This benchmark doesn't use any special JavaScript features or syntax. It only uses standard JavaScript methods and properties (e.g., document.getElementById()
, setAttribute()
, etc.).
Other Alternatives
If you wanted to test other approaches, some alternatives could be:
classList
propertystyle
instead of class
)However, for this specific benchmark, comparing classList.add()
and setAttribute()
is a good starting point, as it highlights the trade-offs between conciseness, readability, and performance.