<div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div><div class="test"></div>
document.querySelectorAll(".test")
document.getElementsByClassName("test")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelector | |
getElementsByClassName |
Test name | Executions per second |
---|---|
querySelector | 923978.8 Ops/sec |
getElementsByClassName | 3568829.5 Ops/sec |
Let's dive into the world of JavaScript benchmarks!
What is being tested?
MeasureThat.net is testing two DOM query methods: querySelectorAll
and getElementsByClassName
. Specifically, it's comparing the performance of these two methods when selecting elements with the class "test" from a HTML document.
Options compared:
There are two main options being compared:
document.querySelectorAll(".test")
: This method returns a NodeList containing all elements that match the specified CSS selector (".test"
).document.getElementsByClassName("test")
: This method returns an HTMLCollection containing all elements with the specified class name ("test"
).Pros and Cons of each approach:
document.querySelectorAll(".test")
:document.getElementsByClassName("test")
:querySelectorAll
, as it only returns a single element.Other considerations:
querySelectorAll
may be slower because of the need to create a new NodeList, while getElementsByClassName
is faster since it directly accesses the element.Library used:
None are mentioned in the provided benchmark definition or result.
Special JS feature or syntax:
None are explicitly mentioned. However, the use of CSS selectors (".test"
and getElementsByClassName
) relies on some JavaScript-specific features:
document.querySelectorAll()
and document.getElementsByClassName()
are built-in methods of the Document object.Other alternatives:
If you need to perform DOM queries in JavaScript, other methods might include:
querySelector
(a similar method to querySelectorAll
, but returns a single element instead of a NodeList).getElementById()
or getElementsByTagName()
(which return an individual element or a collection of elements by ID or tag name, respectively).Element.prototype.matches()
and Element.prototype.matchesAll()
(introduced in ECMAScript 2017, these methods are similar to CSS selectors but return a boolean value indicating whether the element matches or does not match the selector).Keep in mind that each method has its own strengths and weaknesses, and choosing the right one depends on your specific use case and requirements.