<div id="test">Test</div>
document.getElementById("test");
document.querySelector("#test")
window["test"]
test
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getElementById | |
querySelector | |
window | |
direct |
Test name | Executions per second |
---|---|
getElementById | 1003084.6 Ops/sec |
querySelector | 542639.2 Ops/sec |
window | 496772.2 Ops/sec |
direct | 300130.5 Ops/sec |
Let's break down the benchmark and explain what is being tested, compared, and considered.
What is being tested?
The benchmark is designed to compare the performance of three different ways to access an HTML element: getElementById
, querySelector
, and accessing the window object directly (window["test"]
). The test also includes a "direct" option, which bypasses JavaScript altogether by using a property access on the window
object.
Options being compared
The benchmark compares the performance of these three options:
document.getElementById()
function to retrieve an element by its ID.document.querySelector()
function to retrieve an element using a CSS selector.test
property on the window
object, without going through JavaScript.Pros and Cons of each approach
getElementById
, allowing for more flexible selection patterns, and can be faster when used correctly.window
object's property.test
property exists on the window
object, which may not always be the case.Libraries and special JS features
None of the test cases use any libraries or special JavaScript features. The benchmark focuses solely on the core JavaScript methods for accessing elements.
Other alternatives
If the benchmark were to include other options, some potential alternatives could be:
document.querySelectorAll()
: Retrieves all elements matching a CSS selector.document.querySelectorAll()
: Similar to querySelectorAll()
, but returns an HTMLCollection instead of a NodeList.element.style.color = 'red'
).element.getAttribute('id')
or element.value
.However, these alternatives are not currently part of this benchmark.
In summary, this benchmark provides a simple and focused comparison between three common ways to access an HTML element: getElementById
, querySelector
, and direct property access on the window
object.