<div id="foo"></div>
<div class="bar"></div>
<div class="zaz"></div>
<div class="tal"></div>
<div class="quq"></div>
<div class="foo"></div>
document.querySelector('.foo')
document.querySelector('#foo')
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
class | |
id |
Test name | Executions per second |
---|---|
class | 1705673.8 Ops/sec |
id | 1379932.4 Ops/sec |
This benchmark compares the performance of document.querySelector
when selecting elements by ID versus class name.
Options Compared:
.class
(using CSS class): Selects the first element with the specified class attribute. In this case, .foo
.#id
(using HTML ID): Selects the first element with the specified ID attribute. Here, #foo
.Pros and Cons:
#id
(Direct Selection): Generally faster because it relies on a unique identifier directly attached to the element. Browsers have optimized ID lookups for efficiency..class
(Multiple Matching Elements):
Can be slower if there are many elements with the same class. The browser might need to iterate through more potential matches.Other Considerations:
.class
, remember that CSS specificity rules can influence which element is selected if multiple elements have the same class and other conflicting selectors exist. This adds a layer of complexity not present with ID selection.Alternatives:
getElementById()
: A more explicit method for selecting by ID, directly from the DOM object. It offers similar performance to document.querySelector('#id')
.querySelectorAll()
: This method selects all elements matching a given CSS selector (both IDs and classes). Useful if you need multiple matches or want to filter based on attributes or other criteria.Let me know if you'd like more details about any specific aspect of the benchmark!