<div class="test" id="test"></div>
/*When writing async/deferred tests, use `deferred.resolve()` to mark test as done*/
const testElement = document.querySelector(".test");
const [testElement] = document.getElementsByClassName(".test");
const testElement = document.getElementsByClassName(".test")[0];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelector | |
getElementsByClassName with destructuring assignment | |
getElementsByClassName get first element |
Test name | Executions per second |
---|---|
querySelector | 26744934.0 Ops/sec |
getElementsByClassName with destructuring assignment | 15505136.0 Ops/sec |
getElementsByClassName get first element | 21259350.0 Ops/sec |
The benchmark defined in the provided JSON tests the performance of three different methods for selecting DOM elements in JavaScript. Specifically, it compares:
querySelector
:
getElementsByClassName
with destructuring assignment:
getElementsByClassName
method to retrieve elements by their class name and utilizes JavaScript's destructuring assignment to extract the first element from the resulting HTMLCollection.querySelector
for specific class selections because it directly returns a live HTMLCollection. getElementsByClassName
getting the first element directly:
getElementById
: For selecting a single element when you know its ID, which is the fastest option available since it directly accesses the element without needing to parse any selectors.querySelectorAll
: This returns all elements matching a selector, but it won't be as fast as getElementsByClassName
for class-based queries and also returns a static NodeList instead of a live collection.querySelector
method is generally the fastest and most versatile option for selecting DOM elements based on CSS selectors.getElementsByClassName
offers performance benefits for inputs specifying class names, especially when avoiding the overhead of destructuring.In conclusion, choosing between these methods depends on specific needs—whether you prioritize flexibility and readability (favoring querySelector
) or raw performance (favoring getElementsByClassName
).