<div class="name"></div>
<div class="name"></div>
<div class="name"></div>
document.querySelectorAll(".name").forEach((e, i) => {
console.log(e)
})
Array.from(document.getElementsByClassName("name")).forEach((e, i) => {
console.log(e)
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelectorAll | |
getElementsByClassName |
Test name | Executions per second |
---|---|
querySelectorAll | 99385.7 Ops/sec |
getElementsByClassName | 105443.4 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The benchmark compares two ways to iterate over an array of HTML elements: querySelectorAll()
followed by .forEach()
vs getElementsByClassName()
followed by .forEach()
. The goal is to determine which approach is faster and more efficient.
Options Compared
There are only two options being compared:
querySelectorAll()
followed by .forEach()
: This method uses the Document.querySelectorAll()
API to select all elements with a given CSS selector (".name"
in this case), and then iterates over the resulting NodeList using .forEach()
.getElementsByClassName()
followed by .forEach()
: This method uses the document.getElementsByClassName()
API to select all elements with a given class name ("name"
in this case), and then iterates over the resulting HTMLCollection using .forEach()
.Pros and Cons
Here are some pros and cons of each approach:
querySelectorAll()
followed by .forEach()
:
Pros:
querySelectorAll()
is optimized for performance.Cons:
getElementsByClassName()
followed by .forEach()
:
Pros:
document.getElementsByClassName()
can be less optimized than querySelectorAll()
.Cons:
querySelectorAll()
due to the use of an older API.Library Usage
Both benchmarks rely on standard JavaScript APIs, but they don't require any external libraries. However, if you were to modify these benchmarks to work with a different browser or environment, you might need to consider using additional libraries for compatibility or performance optimization.
Special JS Features and Syntax
Neither of the two approaches requires special JavaScript features or syntax. They are straightforward, vanilla JavaScript implementations that should be easily recognizable and maintainable.
Other Alternatives
If you're interested in exploring alternative approaches, here are some options:
Array.from()
with a CSS selector: This method is similar to querySelectorAll()
, but uses the new Array.from()
API to create an array from the DOM elements.Element.querySelectorAll()
on individual elements: Instead of selecting all elements at once, you could use Element.querySelectorAll()
to select elements individually and then iterate over them using .forEach()
.Keep in mind that the best approach will depend on your specific use case, performance requirements, and personal preference.