<div class='testName'>TEST HERE</div>
const el = document.querySelector('div')
el.setAttribute('name', el.getAttribute('class') + ' testClass2')
const el = document.querySelector('div')
el.classList.add('testClass2')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
setAttribute/getAttribute | |
classList |
Test name | Executions per second |
---|---|
setAttribute/getAttribute | 980110.6 Ops/sec |
classList | 751645.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and the pros and cons of each approach.
Benchmark Overview
The measurement is comparing two approaches to set a class on an HTML element in JavaScript:
setAttribute
method to directly set the class attribute.classList.add()
method to add a class to the element's class list.What's being tested?
Options compared:
setAttribute
: Sets the value of an attribute directly.classList.add()
: Adds a class to the element's class list.Pros and Cons of each approach:
setAttribute
Pros:
Cons:
classList.add()
Pros:
Cons:
document.querySelector
)classList
is not availableLibrary used:
In this benchmark, there is no explicit library mentioned. However, the use of document.querySelector()
and classList.add()
implies that these methods are part of the DOM API, which is a standard feature of modern web browsers.
Special JavaScript features or syntax:
None mentioned in this specific benchmark. The code uses standard JavaScript syntax for setting attributes and adding classes.
Other alternatives:
If you needed to set a class on an element without using setAttribute
or classList.add()
, other alternatives might include:
style
attribute directly (e.g., el.style.class = 'newClass'
)className
property of the element's style object (e.g., el.style.className = 'newClass'
)Keep in mind that these alternatives might have different performance characteristics and may not be as efficient as using classList.add()
.
In summary, this benchmark measures the performance difference between two common ways to set classes on HTML elements in JavaScript. While setAttribute
is simple and widely supported, classList.add()
is often faster due to its optimized nature and reliance on modern browser features.