<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 | 8351725.0 Ops/sec |
ID | 11112790.0 Ops/sec |
data attribute | 5555103.0 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Definition
The benchmark measures the performance of different approaches to select an HTML element: by class, by ID, or by data attribute. The benchmark uses JavaScript to query the elements in question and reports the number of executions per second.
Test Cases
There are three test cases:
document.querySelector('.hello');
This test case queries the element with the class "hello" using a class selector.document.getElementById('#hello');
This test case queries the element with the ID "hello" using an ID selector.document.querySelector('[data-hello]');
This test case queries the element with a data attribute named "hello" using a attribute selector.Approaches Compared
The benchmark compares three approaches:
Pros and Cons of Each Approach
Library
None of the test cases use a library, as they are built-in JavaScript functions (document.querySelector()
).
Special JS Features or Syntax
The benchmark uses the following feature:
Html Preparation Code
contains template literals (the string with the \t
character), which are supported in modern JavaScript engines.Other Alternatives
If you want to write a similar benchmark, you can use other approaches such as:
document.querySelectorAll()
instead of querySelectorAll()
.parentNode
, children
, etc.).When creating your own benchmark, make sure to consider factors such as:
Keep in mind that measuring performance can be complex and nuanced; it's essential to carefully design your benchmark to ensure accurate and reliable results.