<div id="select_true" class="aaa bbb selected"></div>
<div id="select_false" class="aaa bbb ccc"></div>
var rxSelected = /\bselected\b/i;
for (var i = 1000; i--; ) {
document.getElementById("select_true").classList.contains("selected");
document.getElementById("select_false").classList.contains("selected");
}
for (var i = 1000; i--; ) {
rxSelected.test(document.getElementById("select_true").className);
rxSelected.test(document.getElementById("select_false").className);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
classList | |
RegExp |
Test name | Executions per second |
---|---|
classList | 3464.3 Ops/sec |
RegExp | 2746.7 Ops/sec |
The benchmark described in the provided JSON compares two different approaches for checking the presence of a class in a DOM element: using the classList.contains
method and using a regular expression with RegExp.test
. Here’s a breakdown of what is being tested, the pros and cons of each method, and some considerations surrounding their usage.
classList.contains()
Method:
classList
property of a DOM element. It checks if a specified class exists in the element's list of classes.classList.contains("selected")
on two DOM elements: one with the class and one without.Regular Expression (RegExp.test
):
className
string of the DOM element./\bselected\b/i
to check the class name.classList.contains()
Pros:
Cons:
RegExp.test
Pros:
classList
, regex might offer a fallback.Cons:
classList.contains()
due to the overhead of evaluating a regular expression and string manipulation.Readability vs. Performance: The choice between these two approaches may depend on the specific needs of the project. If clarity is paramount and performance is acceptable, classList.contains
is a better choice. In cases where regex patterns are required or where there are concerns about compatibility, the second approach might be worth considering.
Regular Expression Syntax: The regex used employs word boundary anchors (\b
) and an ignore case flag (i
). This ensures that the search strictly looks for the "selected" class as a whole word, avoiding partial matches.
Other alternatives for checking class presence in JavaScript include:
Using indexOf()
with className
: One could use element.className.indexOf('selected') !== -1
to check for the presence of the class. This has similar performance drawbacks as regex due to string searching but is an option, especially for developers familiar with older practices.
Using a CSS Framework or Utility Library: Some libraries or frameworks (like jQuery) offer utility functions that can simplify working with DOM elements and classes, although this can lead to increased dependencies in a project.
In summary, the benchmark compares the efficiency of two methods to check class presence, revealing their respective strengths and weaknesses, which can guide developers in choosing the appropriate method based on their specific use case and requirements.