<div class="hello" id="hello" data-hello="hello">Hello</div>
document.querySelector('.hello');
document.querySelector('#hello');
document.querySelector('[data-hello]');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Class | |
ID | |
data attribute |
Test name | Executions per second |
---|---|
Class | 9115264.0 Ops/sec |
ID | 6051660.5 Ops/sec |
data attribute | 5668760.0 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Benchmark Purpose
The purpose of this benchmark is to compare the performance of three different approaches to select an HTML element:
document.querySelector('.hello')
to select elements with the class hello
.document.querySelector('#hello')
to select elements with the ID hello
.document.querySelector('[data-hello]')
to select elements that have a custom attribute data-hello
set.Options Compared
The benchmark compares the execution times of these three approaches on the same HTML document with an element containing the class, ID, and data attribute hello
.
Pros and Cons of Each Approach
Library Used
In this benchmark, no specific library is used beyond the built-in JavaScript DOM API.
Special JS Features/Syntax
None are mentioned in this benchmark.
Other Considerations
The benchmark only measures the execution time of each approach and does not consider other factors like memory usage or CPU overhead.
Alternatives
If you're looking for alternative approaches to select HTML elements, some common ones include:
*
(all elements), .
(elements with a class), or [attribute]
(elements with a custom attribute).querySelectorAll()
method to select multiple elements that match a CSS selector.matches()
method to check if an element matches a CSS selector.These alternatives may have different performance characteristics and use cases, depending on the specific requirements of your project.