<body class="foo bar baz"></body>
var i = 1000;
while (i--) {
if (document.body.matches(".foo.baz")) {
return true;
}
}
var i = 1000;
while (i--) {
if (document.body.classList.contains('foo') && document.body.classList.contains('baz')) {
return true;
}
}
var i = 1000;
while (i--) {
if (['foo', 'baz'].some(className => document.body.classList.contains(className))) {
return true;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
matches | |
classList | |
classList some |
Test name | Executions per second |
---|---|
matches | 16627298.0 Ops/sec |
classList | 9264364.0 Ops/sec |
classList some | 17501172.0 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, the options compared, their pros and cons, and other considerations.
Benchmark Overview
The provided benchmark measures the performance of three different methods to check if an element matches a certain class in JavaScript:
element.matches()
classList.contains()
(on the element
itself)some()
method on the classList
arrayThese methods are compared for their execution speed, and the benchmark aims to identify which one is the fastest.
Options Compared
The three options being tested are:
element.matches()
: This method is introduced in HTML5 and allows checking if an element matches a CSS selector. It's part of the DOM API and is supported by most modern browsers.classList.contains()
: This method is part of the DOM API and allows checking if a class is present on an element. However, it only works when called on the element
itself, not on the element's classList
.some()
method on the classList
array: This method iterates over the classes in the classList
array and returns true
as soon as a match is found.Pros and Cons of Each Approach
element.matches()
classList.contains()
element
itself, not on the element's classList
.some()
method on the classList
arrayclassList.contains()
. However, it may be slower due to the iteration.Library Used
None of these methods rely on any external libraries. They are part of the standard JavaScript DOM API or built-in features.
Special JS Feature/Syntax
None of the tested methods use special JavaScript features or syntax that would affect their performance.
Benchmark Preparation Code
The provided HTML preparation code creates a simple body
element with three classes: foo
, bar
, and baz
.
Other Alternatives
In addition to these three options, other methods can be used to check if an element matches a class, such as:
css-selector
or jsdom
useMemo
hook)However, these alternatives are not part of the standard JavaScript DOM API and may have different performance characteristics.
In summary, the benchmark aims to identify the fastest way to check if an element matches a class in modern browsers. The results will help developers make informed decisions about which method to use for their specific use cases.