<div class="test"></div>
document.querySelector(".test");
document.getElementsByClassName("test")[0];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
QuerySelector | |
GetElementsByClassName[0] |
Test name | Executions per second |
---|---|
QuerySelector | 1465858.6 Ops/sec |
GetElementsByClassName[0] | 1418027.6 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark measures the performance of two approaches to select an HTML element: document.querySelector
and document.getElementsByClassName
. The goal is to determine which approach is faster for retrieving a single element by its class name or CSS selector.
Options Compared
Two options are compared:
document.querySelector
: This method uses CSS selectors to find the first matching element in the document.document.getElementsByClassName
: This method returns an array of all elements with the specified class name, and we're interested in the first (and only) element.Pros and Cons
document.querySelector
:getElementsByClassName[0]
for single-element retrieval, requires more CPU cycles to parse the selector.document.getElementsByClassName
:querySelector
, requires explicit indexing to retrieve individual elements.Library/Functionality
Neither of these functions relies on a library. They are native JavaScript methods built into the DOM API.
However, note that the specific behavior might be affected by CSS-specific features like class
attributes or pseudo-classes like .test: nth-child(1)
in this benchmark.
The alternative for retrieving an element with a given class name would be using a library such as jQuery. It has its own set of methods to retrieve elements, including $
.