<!-- article out start -->
<article>
<!-- article in start -->
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque, nostrum.</p>
<!-- article in end -->
</article>
<!-- article out end -->
<!-- article out start -->
<article>
<!-- article in start -->
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque, nostrum.</p>
<!-- article in end -->
</article>
<!-- article out end -->
<!-- article out start -->
<article>
<!-- article in start -->
<h1>Lorem ipsum</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque, nostrum.</p>
<!-- article in end -->
</article>
<!-- article out end -->
const treeWalker = document.createTreeWalker(
document.body
);
const list = [];
let element;
while (element = treeWalker.nextNode()) {
list.push(element);
}
const list = document.body.querySelectorAll('*');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
TreeWalker | |
querySelectorAll |
Test name | Executions per second |
---|---|
TreeWalker | 328625.9 Ops/sec |
querySelectorAll | 877367.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Overview
The benchmark is designed to compare two approaches for retrieving all elements on a web page:
querySelectorAll('*')
: This method uses the querySelectorAll()
function, which returns a NodeList containing all elements that match the specified selector.document.createTreeWalker()
): This approach uses a TreeWalker to traverse the DOM tree and collect all elements.What's being tested?
The benchmark is testing the performance of these two approaches on different browsers (Chrome 99) and devices (Desktop).
Options compared
The benchmark is comparing:
querySelectorAll('*')
: The first option uses querySelectorAll()
with a wildcard selector ('*'
) to get all elements.document.createTreeWalker()
): The second option uses TreeWalker to traverse the DOM tree and collect all elements.Pros and Cons of each approach
querySelectorAll('*')
:
Pros:
Cons:
querySelector()
or querySelectorAll()
TreeWalker (document.createTreeWalker()
) :
Pros:
querySelectorAll()
, allowing for more specific selectorsCons:
querySelectorAll()
Library used
In this benchmark, no specific library is mentioned. However, in general, TreeWalker is a built-in browser API for navigating the DOM tree.
Special JS features or syntax
There are no special JavaScript features or syntax mentioned in the provided benchmark.
Other considerations
article
elements with similar selectors, which can impact the performance comparison.Alternatives
Other alternatives for retrieving all elements on a web page include:
document.body.querySelectorAll()
with a more specific selector, such as document.body.querySelectorAll('.class')
$()
, $.each()
) to simplify the processArray.from()
and element.matches()