<div class="test"></div>
const x = document.querySelector(".test");
const y = document.getElementsByClassName("test")[0];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelector | |
getElementsByClassName |
Test name | Executions per second |
---|---|
querySelector | 3857881.5 Ops/sec |
getElementsByClassName | 4128331.0 Ops/sec |
I'd be happy to explain the JavaScript microbenchmark being tested on MeasureThat.net.
What's being tested?
The benchmark tests two ways of selecting an HTML element with a specific class: using document.querySelector
and document.getElementsByClassName
. The goal is to determine which method is faster for this particular use case.
Options compared
There are only two options being compared:
document.querySelector(".test")
: This method uses the CSS selector syntax to select an element by its class name. It returns the first matching element, or null
if no element matches.document.getElementsByClassName("test")[0]
: This method uses a legacy way of selecting elements by their class name. It returns an array of all matching elements, and we're only interested in the first element ([0]
).Pros and cons
document.querySelector(".test")
:document.getElementsByClassName("test")[0]
:querySelector
, as it requires parsing the entire element list to find the first match.Library usage
Neither of these methods uses a specific library. They are built-in DOM APIs provided by modern web browsers.
Special JS feature
This benchmark doesn't use any special JavaScript features or syntax beyond what's required for the test cases. If you're interested in testing more advanced features, MeasureThat.net has a vast range of benchmarks covering various topics.
Alternatives
If you're looking for alternative ways to select elements with a class name, some other methods include:
document.querySelectorAll(".test")
: Returns an array of all matching elements. If you only need the first element, you can use [0]
, like document.getElementsByClassName
.element.classList.contains("test")
: Checks if an element has a specific class without selecting it. You would then need to select the element using another method.Keep in mind that these alternatives may have their own trade-offs and usage scenarios. MeasureThat.net's benchmarks are designed to help you compare performance across different browsers, libraries, and techniques.