<div class="hello" id="hello" data-hello>Hello</div>
document.querySelector('.hello');
document.getElementById('hello');
document.querySelector('[data-hello]');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Class | |
ID | |
data attribute |
Test name | Executions per second |
---|---|
Class | 3309653.8 Ops/sec |
ID | 5566428.0 Ops/sec |
data attribute | 2100009.0 Ops/sec |
Benchmark Overview
The provided JSON represents a JavaScript microbenchmark test suite on the MeasureThat.net website. The benchmark compares the performance of three different methods to select an HTML element: document.querySelector('.hello')
, document.getElementById('hello')
, and document.querySelector('[data-hello]')
. These methods are commonly used in web development to retrieve elements from the DOM.
Methods Comparison
The three methods being compared have different advantages and disadvantages:
document.querySelector('.hello')
):document.getElementById('hello')
):querySelector
.document.querySelector('[data-hello]')
):Library Usage
In this benchmark, none of the methods rely on a specific library. However, the querySelector
method uses the Web API's querySelector()
function, which is part of the ECMAScript standard and supported by most modern browsers.
Special JavaScript Features/Syntax
There are no special JavaScript features or syntax used in this benchmark. The code only uses basic DOM methods and standard JavaScript syntax.
Other Alternatives
If you need to select elements from a different HTML structure or with different attributes, you might consider alternative methods:
document.getElementsByClassName('hello')
: Selects an element by its class name using the getElementsByClassName()
method.document.querySelectorAll('.hello')
: Selects multiple elements by their class names using the querySelectorAll()
method.document.querySelector('[attribute="value"]')
: Selects an element by a specific attribute value.Keep in mind that these alternatives might have different performance characteristics, and it's essential to test them in your specific use case.
Benchmark Result Interpretation
The latest benchmark result shows the execution rate per second for each method on a Chrome 90 browser running on a Mac OS X 10.15.7 device. The results indicate:
document.getElementById('hello')
) is the fastest, with an average of 4719036 executions per second.document.querySelector('[data-hello]')
) is slower, with an average of 2542531 executions per second.document.querySelector('.hello')
) is the slowest, with an average of 2083029 executions per second.These results are specific to this benchmark and might vary depending on your use case and browser/OS combination.