<div id="foo" class="test"></div>
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
if (element.className.indexOf("test") !== -1) {}
}
var element = document.getElementById("foo");
var i = 1000;
while (i--) {
element.classList.contains("test");
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
className | |
classList |
Test name | Executions per second |
---|---|
className | 48034.4 Ops/sec |
classList | 15274.7 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The benchmark compares two approaches to check if an HTML element has a specific class: className.indexOf()
and classList.contains()
. The goal is to measure which approach is faster.
Options Compared
The benchmark tests two options:
className.indexOf()
: This method searches for the specified class within the className
property of the element.classList.contains()
: This method checks if a specific value exists in the classList
collection of the element.Pros and Cons
className.indexOf()
: Pros:classList
Cons:classList.contains()
: Pros:indexOf()
classList
API, which might be unsupported in older browsersLibrary Usage
The benchmark uses the document.getElementById()
function to retrieve an HTML element with the id "foo". This is a standard JavaScript method for retrieving elements by their ID.
Special JS Feature/Syntax
None mentioned. Both test cases use standard JavaScript features and syntax.
Other Considerations
When writing benchmarks like this, it's essential to consider factors such as:
Alternatives
If you want to explore alternative approaches, consider these:
classList.toggle()
instead of classList.contains()
. This method adds or removes the specified class from the element's list, which might be faster in some cases.Keep in mind that microbenchmarking can be complex, and results may vary depending on the specific use case and environment.
I hope this explanation helps!