<div id="div"></div>
div.innerHTML = Array(1000).fill(0).map((el, i) => `<div id="id${i}" class="test${i}"></div>`)
Array(1000).fill(0).map((el, i) => document.getElementById(`id${i}`).className)
Array(1000).fill(0).map((el, i) => document.querySelector(`#id${i}`).className)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getElementById | |
querySelector |
Test name | Executions per second |
---|---|
getElementById | 1387.7 Ops/sec |
querySelector | 47.4 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The benchmark is designed to compare the performance of document.getElementById
and document.querySelector
in selecting elements by ID. The test case consists of two individual tests:
getElementById
querySelector
Both tests create an array of 1000 elements, each with a unique ID (id${i}
) and a class name (test${i}
). The script preparation code generates these elements using JavaScript, while the HTML preparation code creates a container element (div
) to hold the generated elements.
Benchmarking Options
The two options being compared are:
document.getElementById
: This method retrieves an element by its ID.document.querySelector
: This method retrieves one or more elements that match a specific CSS selector (in this case, #id${i}
).Pros and Cons of Each Approach
document.getElementById
Pros:
Cons:
querySelector
, as it requires a specific ID.document.querySelector
Pros:
getElementById
, as it can match elements using CSS selectors.Cons:
Library Usage
There is no library used in this benchmark. Both document.getElementById
and document.querySelector
are built-in methods of the Document object.
Special JavaScript Feature or Syntax
None mentioned.
Other Considerations
When evaluating the performance of these two methods, it's essential to consider the following factors:
Alternatives
If you're looking for alternative benchmarking tools or approaches, consider the following options:
In conclusion, the MeasureThat.net benchmark provides a clear comparison between document.getElementById
and document.querySelector
, highlighting their respective strengths and weaknesses. By understanding the pros and cons of each approach, you can make informed decisions about which method to use in your own JavaScript applications.