<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<a></a>
<a></a>
<a></a>
<a></a>
<a></a>
<a></a>
<a></a>
<a></a>
<a></a>
<a></a>
document.querySelectorAll('a').forEach((element) => {});
const tags = document.getElementsByTagName('a');
const l = tags.length;
for (let i = 0; i < l; i++) {}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelectorAll | |
getElementsByTagName |
Test name | Executions per second |
---|---|
querySelectorAll | 295476.6 Ops/sec |
getElementsByTagName | 1509302.5 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
What is being tested?
The benchmark compares the performance of two DOM querying methods:
querySelectorAll()
(short for "query selector all")getElementsByTagName()
Both methods are used to retrieve a collection of elements that match a specific CSS selector or tag name, respectively. However, they have different implementations and usage patterns.
Options being compared:
The benchmark compares the performance of each method with a constant length of 10 elements (in this case, <a>
tags). The test is designed to measure which method is faster for small to medium-sized collections.
Pros and Cons of each approach:
querySelectorAll()
:"a, img"
).getElementsByTagName()
:Library and purpose:
There is no specific library being used in this benchmark. However, the querySelectorAll()
method relies on the W3C standard for CSS selectors, which is a widely adopted and maintained specification.
Special JavaScript feature or syntax:
None mentioned in this benchmark.
Other alternatives:
For larger collections, other DOM querying methods may be faster:
getElementsByClassName()
: Similar to querySelectorAll()
but uses the class name instead of a CSS selector.getElementById()
: Retrieves an element by its ID attribute instead of using a CSS selector or tag name.These alternatives may have different performance characteristics, depending on the specific use case and collection size.
Benchmark preparation code:
The script preparation code is empty, indicating that no additional setup or processing is needed for these benchmark cases. The HTML preparation code creates an HTML document with 10 <div>
elements and 10 <a>
tags, which will be used as the test subject.