<div id='hello'></div>
<div id='there'></div>
console.log(document.querySelector('#hello'));
document.querySelectorAll('#hello').forEach((el) => { console.log(el); });
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
QuerySelector | |
QuerySelectorAll + ForEach |
Test name | Executions per second |
---|---|
QuerySelector | 90697.1 Ops/sec |
QuerySelectorAll + ForEach | 93066.4 Ops/sec |
Let's break down the benchmark test.
What is being tested?
The benchmark is testing two approaches to select and log an element from HTML:
console.log(document.querySelector('#hello'));
: This approach uses the querySelector
method, which selects the first element that matches the specified CSS selector.document.querySelectorAll('#hello').forEach((el) => { console.log(el); });
: This approach uses the querySelectorAll
method to select all elements that match the specified CSS selector, and then iterates over the result using the forEach
method, logging each element.What options are being compared?
The two approaches being tested are:
querySelector
(Approach 1)querySelectorAll
followed by forEach
(Approach 2)Pros and Cons of each approach:
Approach 1: console.log(document.querySelector('#hello'));
Pros:
Cons:
Approach 2: document.querySelectorAll('#hello').forEach((el) => { console.log(el); });
Pros:
Cons:
Other considerations:
querySelectorAll
followed by forEach
can be less efficient if only one element matches the selector, as it will still perform a full query.Array.prototype.forEach.call()
or a for...of loop instead of vanilla forEach
, which provides better support for handling arrays and other iterable objects.Library usage:
In this benchmark, no libraries are explicitly used. However, the document
object is part of the browser's DOM (Document Object Model), which is a built-in JavaScript API.
Special JS features or syntax:
There are no special JavaScript features or syntax mentioned in this benchmark. The test only uses standard JavaScript methods and properties, such as querySelector
, querySelectorAll
, forEach
, and console.log
.
Alternatives:
Other alternatives to the two approaches being tested could include:
Array.prototype.find()
or a similar method to find the first matching elementdocument.querySelector('#hello[attr="value"]')
)Keep in mind that these alternatives may not be relevant or applicable to all use cases, and the benchmark's focus is on comparing two specific approaches.