<div id="test_element_id" class="test_element_class"></div>
var el = document.getElementById('test_element_id');
var el = document.querySelector('#test_element_id');
var el = document.getElementsByClassName('test_element_class')[0];
var el = document.querySelectorAll('.test_element_class')[0];
var el = document.querySelector('.test_element_class');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getElementById | |
querySelector | |
getElementsByClassName | |
querySelectorAll | |
querySelector class |
Test name | Executions per second |
---|---|
getElementById | 7691434.0 Ops/sec |
querySelector | 4139755.0 Ops/sec |
getElementsByClassName | 3872343.8 Ops/sec |
querySelectorAll | 1773960.2 Ops/sec |
querySelector class | 3722568.0 Ops/sec |
I'll explain the benchmark in detail.
What is being tested?
The provided JSON represents a JavaScript microbenchmarking test case, specifically comparing the performance of four different methods to select an element from a HTML document: getElementById
, querySelector
with an ID selector, getElementsByClassName
with a class selector, and querySelectorAll
with a class selector. The test also includes a variant that selects elements by their class using only querySelector
.
Options being compared
Here's a brief overview of each option:
#test_element_id
) as a string parameter and returns the first element that matches the selection criteria..test_element_class
) as a string parameter and returns a NodeList containing all elements that match the selection criteria.Pros and Cons
Here's a brief summary of each option:
getElementById
for multiple element IDs.getElementById
.Library and purpose
In this benchmark, none of the libraries are explicitly mentioned. However, document.querySelector
and document.querySelectorAll
are part of the HTML5 DOM API, which is a built-in JavaScript library provided by modern browsers.
Special JS features or syntax
There's no special JS feature or syntax used in this benchmark, as it only involves standard JavaScript methods and CSS selectors.
Other alternatives
If you're looking for alternative methods to select elements, here are some options:
getElementsByClassName
, but takes an index instead of classes.with
nodeListiterator: Instead of using the entire NodeList returned by
querySelectorAll, you can use a
nodeList` iterator to iterate over the elements, which can be more memory-efficient.Keep in mind that these alternatives may have different performance characteristics and usage scenarios compared to the methods being tested in this benchmark.