<div class="foo">test</div>
<div class="bar">test</div>
<div class="foo">test</div>
<div class="bar">test</div>
<div class="foo">test</div>
<div class="bar">test</div>
<div class="foo">test</div>
<div class="bar">test</div>
<div class="foo">test</div>
<div class="bar">test</div>
Array.from(document.getElementsByClassName("foo")).forEach(item => {if(item.textContent === "test"){console.log("match")}});
document.querySelectorAll("foo").forEach(item => {if(item.textContent === "test"){console.log("match")}});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
.getElementsByClassName() | |
.querySelectorAll() |
Test name | Executions per second |
---|---|
.getElementsByClassName() | 306773.7 Ops/sec |
.querySelectorAll() | 17698132.0 Ops/sec |
Let's dive into the benchmark.
The provided JSON represents a JavaScript microbenchmark test case on MeasureThat.net, titled ".getElementsByClassName() vs. .querySelectorAll()". This test compares the performance of two different approaches to retrieve elements from an HTML document:
getElementsByClassName()
: This method returns a live HTMLCollection, which is an array-like object containing all elements that match the specified class name.querySelectorAll()
: This method also returns a NodeList (a static collection of nodes), which contains all elements that match the specified CSS selector.Comparison:
The test case uses two individual scripts:
Array.from(document.getElementsByClassName("foo")).forEach(...)
: This script uses getElementsByClassName()
to retrieve an array of elements with class "foo" and then iterates through it using forEach()
.document.querySelectorAll("foo").forEach(...)
: This script uses querySelectorAll()
to retrieve a NodeList of elements that match the CSS selector "foo" and then iterates through it using forEach()
.Options compared:
The two options being compared are:
Pros and Cons:
getElementsByClassName()
:querySelectorAll()
:Library/Functionality:
In this test case, no external library or functionality is used. The Array.from()
method is used to convert the HTMLCollection returned by getElementsByClassName()
to an array-like object.
Special JS feature/Syntax:
The forEach()
method is a standard JavaScript feature that iterates over an array-like object or an iterable.
Other alternatives:
If you were to optimize this benchmark, you could also consider using:
Element.matches()
: A more modern way to check if an element matches a CSS selector.Array.prototype.forEach.call()
: An alternative way to iterate over the result set returned by getElementsByClassName()
.Keep in mind that these alternatives may not provide a significant performance boost unless you're working with very large datasets or performance-critical code.