<div class="hello" id="hello" data-hello="foo bar baz">Hello</div>
document.querySelector('.hello');
document.querySelector('#hello');
document.querySelector('[data-hello]');
document.querySelector('[data-hello~="foo"]');
document.querySelector('[data-hello~="bar"]');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Class | |
ID | |
data attribute | |
attribute selector ~ one | |
attribute selector ~ second |
Test name | Executions per second |
---|---|
Class | 3299271.8 Ops/sec |
ID | 2512194.2 Ops/sec |
data attribute | 2272310.2 Ops/sec |
attribute selector ~ one | 2105571.2 Ops/sec |
attribute selector ~ second | 2076892.1 Ops/sec |
Let's break down the provided JSON and explain what's being tested, the options compared, their pros and cons, and other considerations.
Benchmark Definition
The benchmark definition is a set of rules that describes how to create a test case for measuring JavaScript performance. It consists of two parts:
<div>
element with an id
, data-hello
attribute, and some text content.Individual Test Cases
There are four individual test cases defined in the JSON:
document.querySelector('.hello');
.classSelector
method to select an element based on its class attribute.document.querySelector('#hello');
#idSelector
method to select an element based on its id
attribute.document.querySelector('[data-hello]');
[attribute Selector]
method to select an element based on a custom attribute named hello
.document.querySelector('[data-hello~="foo"]');
document.querySelector('[data-hello~="bar"]');
[attributeSelector]
method with a regular expression to select an element based on a custom attribute named hello
, where the value must contain "foo" or "bar", respectively.Pros and Cons
Each approach has its own trade-offs:
querySelectorById
method's implementation, which involves a database-like search.Other Considerations
document.getElementById('elementId');
document.getElementsByTagName('tagName');
Element.prototype.querySelector('[attributeSelector]')
Note that these alternatives might have different performance characteristics and use cases.
Conclusion
The benchmark compares the performance of different JavaScript selectors for selecting HTML elements. Each approach has its pros and cons, and understanding these trade-offs can help developers optimize their code for better performance in real-world applications.