<div name='test' id='test' class='test'></div>
document.querySelector('#test')
document.getElementsByName('div[name="#test"]')
document.getElementById('test')
document.getElementsByClassName(".test")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelector | |
getElementsByName | |
getElementById | |
getElementsByClassName |
Test name | Executions per second |
---|---|
querySelector | 3842833.5 Ops/sec |
getElementsByName | 7834678.5 Ops/sec |
getElementById | 6968310.0 Ops/sec |
getElementsByClassName | 7518261.5 Ops/sec |
Overview of the Benchmark
The provided benchmark tests the performance of four different methods to select elements from an HTML document in JavaScript:
document.querySelector('#test')
document.getElementsByName('div[name="#test"]')
document.getElementById('test')
document.getElementsByClassName('.test')
Library Used
None of the test cases uses a specific library, but they do use native browser APIs.
Options Compared
The benchmark compares the performance of four different methods:
querySelector
: Uses the querySelector
method to select an element by its ID.getElementsByName
: Uses the getElementsByName
method to select elements by their name attribute.getElementById
: Uses the getElementById
method to select an element by its ID (similar to querySelector
, but without the $=
syntax).getElementsByClassName
: Uses the getElementsByClassName
method to select elements by their class attribute.Pros and Cons of Each Approach
querySelector
:getElementsByName
:getElementById
:querySelector
.querySelector
, as it only selects by ID.getElementsByClassName
:Special JS Feature/Syntax
The querySelector
method uses a CSS-like syntax to select elements. It was introduced in ECMAScript 5 and has become widely supported across browsers.
Other Alternatives
If you want to explore other alternatives, here are a few:
document.evaluate
: A more powerful and flexible method for selecting elements using XPath expressions.CSS selectors
: Some libraries, like jQuery, use CSS selectors to select elements. These can be more efficient than native browser APIs in some cases.Keep in mind that the performance differences between these methods may vary depending on the specific use case and browser implementation.
Benchmark Preparation Code
The Html Preparation Code
is a simple <div>
element with an ID, class, and name attribute:
<div name='test' id='test' class='test'></div>
This code sets up a basic HTML structure for the benchmark to run on.