<div id="testdiv1">
<div id="testdiv2" class="unique2" name="unique2" data-unique="2">test</div>
<div id="testdiv3" class="unique3" name="unique3" data-unique="3">test</div>
</div>
var i, imax;
var doc = document;
var test = doc.getElementById('testdiv2').innerHTML;
var test = doc.getElementsByClassName('unique2')[0].innerHTML;
var test = doc.getElementsByName('unique2')[0].innerHTML;
var test = doc.querySelectorAll("[data-unique='2']")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getElementById | |
getElementsByClassName | |
getElementsByName | |
querySelectorAll |
Test name | Executions per second |
---|---|
getElementById | 965400320.0 Ops/sec |
getElementsByClassName | 6526180.0 Ops/sec |
getElementsByName | 6459203.5 Ops/sec |
querySelectorAll | 1031766.4 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared options, pros and cons of each approach, and other considerations.
What's being tested?
The test measures the performance of different methods to retrieve a single DOM element:
getElementById
getElementsByClassName
getElementsByName
(note: this is not a standard method in JavaScript; it might be a typo or a custom implementation)querySelectorAll
Options comparison
Here's a brief overview of each option, their pros and cons:
getElementById
getElementsByClassName
getElementById
due to the overhead of searching for matching class namesgetElementsByName
(assuming it's a custom implementation)querySelectorAll
[data-unique='2']
Library usage
In this benchmark, document
is used as a global variable to access the DOM. The document
object provides various methods for interacting with the DOM, including getElementById
, getElementsByClassName
, and others.
Special JS feature or syntax
The test uses a custom attribute data-unique
on one of the element's classes. This is not a standard HTML attribute and might be specific to this benchmark's use case. It's used as a selector in the querySelectorAll
option.
Other considerations
When choosing an approach for retrieving a single DOM element, you should consider factors such as:
Alternatives
Other methods for retrieving a single DOM element include:
getElementsByTagName
: Returns an array of elements with the specified tag name.querySelector
and querySelectorAll
(but with different selectors): These can be more complex than simple attribute-based selectors.Keep in mind that each method has its own strengths and weaknesses, and the choice ultimately depends on your specific use case and performance requirements.