<div id="test">Testing</div>
var el = document.getElementById('test');
el.setAttribute('mytest', 'true')
el.classList.add('mytest')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
setAttribute | |
classList.add |
Test name | Executions per second |
---|---|
setAttribute | 9292315.0 Ops/sec |
classList.add | 4873082.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and what pros and cons of each approach are.
Benchmark Definition
The benchmark is testing two different approaches to add a class or attribute to an HTML element: classList.add
vs setAttribute
.
What's being tested?
In this case, we're comparing the performance of:
classList.add
: This method adds a specified class to an element. It's part of the W3C DOM specification and is supported by most modern browsers.setAttribute
: This method sets the value of an attribute on an element. In this case, we're setting the mytest
attribute with the value true
.Options compared
The two options are being compared in terms of execution time (measured in executions per second). The benchmark aims to determine which approach is faster.
Pros and Cons of each approach:
classList.add
:setAttribute
:Library usage
Neither classList.add
nor setAttribute
rely on a specific library. They are both built-in DOM methods.
Special JS features or syntax
This benchmark does not use any special JavaScript features or syntax that would affect the execution or outcome of the test.
Other alternatives
If you were to implement this benchmark yourself, alternative approaches might include:
element.style
instead of classList.add
or setAttribute
Keep in mind that these alternatives would likely have different performance characteristics and may not be as widely supported across browsers.
Benchmark preparation code
The provided script preparation code is:
var el = document.getElementById('test');
This sets up an HTML element with the ID test
and assigns it to a variable named el
. The corresponding HTML file should include:
<div id="test">Testing</div>
This creates an empty <div>
element with the specified ID, which is then manipulated by the JavaScript code.
Latest benchmark result
The provided raw UAFS (User Agent Fingerprint String) data shows the results for two Firefox 130 runs:
setAttribute
: approximately 9.29 million executions per secondclassList.add
: approximately 4.83 million executions per secondPlease note that these values are specific to the given test scenario and may vary depending on your environment, browser version, and other factors.