<div id="foo" class="test"></div>
let el = document.getElementById("foo"), i = 10000;
while (i--) {
el.className?.includes("test");
}
let el = document.getElementById("foo"), i = 10000;
while (i--) {
el.classList?.contains("test");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className.includes | |
classList.contains |
Test name | Executions per second |
---|---|
className.includes | 7033.0 Ops/sec |
classList.contains | 1399.7 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Definition
The benchmark is defined in JSON, which provides information about the test case. Here's a summary:
Individual Test Cases
There are two individual test cases:
className.includes
:<div id="foo" class="test"></div>
, which creates a DOM element with an ID of "foo" and a class of "test".document.getElementById("foo")
.i
to 10,000.includes()
method.classList.contains
:<div id="foo" class="test"></div>
.contains()
method on the element's classList
.What's being tested?
Both test cases are measuring the performance of two different ways to check if a string contains another string within an HTML element's class name or list of classes.
In other words, the benchmark is comparing the speed of:
includes()
method on a stringcontains()
method on the classList
property of an HTML elementLibrary and Purpose
The classList
property is part of the W3C DOM specification and provides a way to access and manipulate an element's class list. It's a built-in feature in modern browsers.
Special JS Feature or Syntax
There are no special JavaScript features or syntaxes being tested here, as both test cases use standard language constructs (loops, string comparison).
Pros and Cons of Different Approaches
Here are some pros and cons of using includes()
vs. contains()
:
includes()
:contains()
:It's worth noting that modern browsers have optimized includes()
and contains()
methods, so the performance difference between these two approaches may be smaller than expected.
Alternatives
There are other ways to achieve similar results without using classList.contains
:
/\btest\b/.test(el.className)
).contains()
function.However, these alternatives may not be as efficient or straightforward to use as the built-in classList.contains
method.