<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 | 1183636.2 Ops/sec |
getElementsByClassName | 3980943.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
What is tested?
The provided JSON represents a benchmark test that compares two methods for selecting elements in HTML documents:
document.querySelectorAll(".test")
document.getElementsByClassName(".test")
These methods are used to retrieve all elements with a specific class attribute.
Options compared
The two options being compared are:
querySelectorAll
(also known as querySelectorAll()
): returns a live HTMLCollection of all matching elements.getElementsByClassName
(also known as getElementsByClassName(string)
): returns a live HTMLCollection of all elements with the specified class name.Pros and Cons
document.querySelectorAll(".test")
:document.getElementsByClassName(".test")
:querySelectorAll
, as it only supports single class names.Library usage
None of the test cases use any external libraries. The code is self-contained and uses only the built-in JavaScript DOM API.
Special JS feature or syntax
There are no special JavaScript features or syntax used in this benchmark.
Benchmark preparation code
The provided HTML preparation code creates a simple HTML document with multiple elements having the class "test". This allows the test cases to accurately measure the performance of each method.
Alternative approaches
Other alternatives for selecting elements include:
document.querySelector(".test")
: similar to querySelectorAll
, but returns only the first matching element.document.querySelectorAll("div.test")
: selects elements with a specific tag name and class.Element.prototype.matches()
: a newer API introduced in ECMAScript 2017 (ES2017), which provides more powerful selectors.These alternative approaches may offer different performance characteristics, depending on the use case and browser support.