<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
const allDivs = document.querySelectorAll('div');
allDivs.forEach(function (div) {
console.log(div);
});
const allDivs = document.getElementsByTagName('div');
const arrayAllDivs = Array.from(allDivs);
arrayAllDivs.forEach(function (div) {
console.log(div);
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelectorAll | |
getElementsByTagName |
Test name | Executions per second |
---|---|
querySelectorAll | 42231.0 Ops/sec |
getElementsByTagName | 34647.6 Ops/sec |
Let's dive into the explanation of the provided benchmark.
What is being tested?
The benchmark compares two methods for selecting all elements with the tag name 'div' in an HTML document: querySelectorAll
and getElementsByTagName
.
Options compared
The two options are compared:
Pros and Cons
getElementsByTagName
, as it leverages the browser's CSS selector engine.querySelectorAll
due to its reliance on the browser's built-in DOM implementation.Library usage
Neither of these methods relies on a specific library, but they do utilize the Document Object Model (DOM) of HTML documents. The DOM provides an interface for manipulating and querying elements in an HTML document.
Special JavaScript features or syntax
None are mentioned in this benchmark.
Other alternatives
If you were to rewrite these benchmarks using more modern JavaScript features, you could use:
Array.from()
with a CSS selector: const allDivs = Array.from(document.querySelectorAll('div'));
Array.prototype.forEach
method: document.querySelectorAll('div').forEach(function (div) { console.log(div); });
However, these alternatives are not directly comparable to the original querySelectorAll
and getElementsByTagName
methods.
Benchmark preparation code
The provided HTML preparation code creates a single-page document with 11 <div>
elements. The script preparation codes for each test case select all <div>
elements using their respective methods.
Latest benchmark result
The latest results show that querySelectorAll
is slightly faster than getElementsByTagName
, executing approximately 76,000 more times per second on the provided hardware configuration.