<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>
const allDivsAndAnchors = Array.from(document.querySelectorAll('div, a'));
allDivsAndAnchors.forEach(function (el) {});
const allDivs = document.getElementsByTagName('div');
const allAnchors = document.getElementsByTagName('a');
const allDivsAndAnchors = Array.from(allDivs).concat(Array.from(allAnchors));
allDivsAndAnchors.forEach(function (el) {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelectorAll | |
getElementsByTagName |
Test name | Executions per second |
---|---|
querySelectorAll | 65397.2 Ops/sec |
getElementsByTagName | 72217.5 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Overview
The benchmark compares two approaches for selecting multiple elements in HTML: querySelectorAll
and getElementsByTagName
. The test creates an HTML document with several <div>
and <a>
elements and measures which approach is faster.
Options Compared
Two options are compared:
<div>
and <a>
elements.document.getElementsByTagName('div')
or document.getElementsByTagName('a')
). The results are then concatenated using Array.from()
.Pros and Cons
Here's a brief overview of each approach:
Pros:
getElementsByTagName
, as it allows for more complex selectors.Cons:
Pros:
querySelectorAll
.Cons:
querySelectorAll
, since only a single element type can be specified.Array.from()
to combine results from multiple calls.Library/Tool Used
None, as this is a built-in JavaScript API for web developers.
Special JS Features/Syntax
No special features or syntax are used in the benchmark. The test only relies on standard JavaScript and HTML elements.
Other Alternatives
If you need to compare performance of other selection methods, here are some alternatives:
querySelector
: Similar to querySelectorAll
, but returns a single element instead of all matching elements.getElementsByClassName
(not shown in this benchmark): Selects elements by their class names.querySelectorAll([selector1, selector2])
: Allows for multiple selectors to be combined using the ||
operator.These alternatives can be used to compare performance with different selection methods, such as:
getElementsByTagName
querySelector
Keep in mind that each approach has its strengths and weaknesses, and some may perform better for specific use cases. The benchmark provides a useful comparison of these approaches, but you should consider the specific requirements of your project when choosing an implementation.