<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) {});
const allDivs = document.getElementsByTagName('div');
const arrayAllDivs = Array.from(allDivs);
arrayAllDivs.forEach(function (div) {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelectorAll | |
getElementsByTagName |
Test name | Executions per second |
---|---|
querySelectorAll | 1012977.6 Ops/sec |
getElementsByTagName | 824633.9 Ops/sec |
Let's break down the provided benchmark definition and test cases to understand what's being tested.
Benchmark Definition Json
The benchmark defines two tests: querySelectorAll
and getElementsByTagName
. The Script Preparation Code
is empty, which means that no JavaScript code is executed before running the test. The Html Preparation Code
creates a set of 10 <div>
elements, which will be used as targets for the tests.
Test Case 1: querySelectorAll
The test case uses the document.querySelectorAll('div')
method to select all <div>
elements on the page. It then iterates over the resulting NodeList using the forEach
method.
Here's a brief explanation of what's being tested:
querySelectorAll
versus other methods to select elements.Pros and Cons
Test Case 2: getElementsByTagName
The test case uses the document.getElementsByTagName('div')
method to select all <div>
elements on the page. It then converts the resulting HTMLCollection to an array using Array.from()
and iterates over it using forEach
.
Here's a brief explanation of what's being tested:
getElementsByTagName
versus other methods to select elements.Pros and Cons
querySelectorAll
, as it avoids the creation of a NodeList.Other Considerations
Array.from()
to convert an HTMLCollection to an array adds some overhead, but can provide more control over the result.Library Used: None
There are no external libraries used in these test cases. However, it's worth noting that querySelectorAll
is a part of the W3C DOM specification and is supported by most modern browsers.
Special JS Feature/ Syntax: None
There are no special JavaScript features or syntax used in these test cases. The focus is on comparing performance between two different methods for selecting elements.
Alternative Approaches
Other approaches to select elements include:
document.getElementById()
: Selects a single element by its ID.document.querySelector()
: Selects a single element using CSS selectors.:first-child
or [data-id]
.Each of these methods has its own trade-offs and may be more or less suitable depending on the specific use case.