<div id="foo" class="folder open filtered"></div>
var p = document.getElementById("foo");
var i = 1000;
while (i--) {
if (p.className.indexOf('folder') != -1)
p.className = 'folder open'+
(p.className.indexOf('filtered') != -1 ? 'filtered ' : '')
+'parent';
}
var p = document.getElementById("foo");
var i = 1000;
while (i--) {
if(p.classList.contains("folder")) {
p.classList.add('open', 'parent');
if (p.className.indexOf('filtered') != -1)
p.classList.add('filtered');
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
classList |
Test name | Executions per second |
---|---|
className | 1104.0 Ops/sec |
classList | 379.8 Ops/sec |
I'll break down the benchmark definition and test cases for you.
What is tested on the provided JSON?
The provided JSON represents two microbenchmarks that compare the performance of JavaScript classes (className
) with class lists (classList
). The benchmarks test the addition and updating of CSS classes to an HTML element with a specific ID (foo
).
Options compared:
There are two approaches being compared:
className
:className
property to update the classes.classList
:classList
property to add and remove classes.contains()
.add()
.Pros and Cons:
Using className
:
Pros:
className
property update)Cons:
indexOf()
.Using classList
:
Pros:
contains()
method for checking class presence.Cons:
classList
property updates).Other considerations:
Both approaches have their advantages and disadvantages. The choice between them depends on the specific use case and performance requirements.
Library usage:
There is no explicit library usage mentioned in the benchmark definition, but it's worth noting that both approaches rely on modern JavaScript features (classes and classList
property).
No special JavaScript feature or syntax is used in this benchmark.
Alternative approaches:
Other alternatives to consider for updating CSS classes include:
toggleClass()
method.classList
or className
.CSSStyleDeclaration
and DOMTokenList
to update CSS classes.Keep in mind that these alternatives may have different performance characteristics and implementation complexities compared to the benchmarked approaches.