<div class="test" id="test"></div>
document.querySelector(".test")
document.querySelectorAll(".test")
document.getElementsByClassName(".test")
document.querySelector("#test")
document.getElementById("test")
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelector | |
querySelectorAll | |
getElementsByClassName | |
querySelector (ID) | |
getElementsByID |
Test name | Executions per second |
---|---|
querySelector | 19193338.0 Ops/sec |
querySelectorAll | 6439661.0 Ops/sec |
getElementsByClassName | 37191108.0 Ops/sec |
querySelector (ID) | 8638648.0 Ops/sec |
getElementsByID | 26794146.0 Ops/sec |
Let's break down what is being tested in this benchmark.
The test cases are designed to compare the performance of different methods for selecting elements from an HTML document:
document.querySelector('.test')
: This method selects the first element with the class test
that matches the specified selector. It returns a single element.document.querySelectorAll('.test')
: This method selects all elements with the class test
that match the specified selector. It returns an HTMLCollection of multiple elements.document.getElementsByClassName('test')
: This method selects all elements with the class test
. Note that this method does not consider the id
attribute, unlike querySelector
.document.querySelector('#test')
: This method selects the first element with the ID test
that matches the specified selector.document.getElementById('test')
: This method selects the element with the ID test
. Unlike getElementsByClassName
, it only returns a single element.Now, let's discuss the pros and cons of each approach:
querySelector
because it has to iterate over all elements with the specified class. However, it can be useful when you need to select multiple elements based on their class.querySelector
because it has to iterate over all elements with the specified ID. It's mainly used for compatibility reasons or when you need to select an element by its ID only.It's worth noting that the performance difference between these methods can be significant, especially when dealing with large datasets.
As for libraries, none are explicitly mentioned in this benchmark.
The test cases do not use any special JavaScript features or syntax. However, it's always a good idea to consider factors like code organization, maintainability, and scalability when writing benchmarks.
Other alternatives to these methods include:
document.querySelectorAll('*')
to select all elements on the page, but this can be slower because it returns an HTMLCollection of all elements.Array.prototype.filter()
method to implement your own selector functionality.