<style>.searchMe {border: 1px sold red;}</style>
<table id="tableTest"></table>
for(var i=0; i<10000; ++i)
{
var cell = tableTest.insertRow(-1).insertCell(-1);
if(i%2==0)
cell.classList.add('searchMe');
}
var found = tableTest.getElementsByClassName('searchMe');
tableTest.rows[0].cells[0].textContent = found.length;
var found = tableTest.querySelectorAll('.searchMe');
tableTest.rows[0].cells[0].textContent = found.length;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
getElementsByClassName | |
querySelectorAll |
Test name | Executions per second |
---|---|
getElementsByClassName | 224153.1 Ops/sec |
querySelectorAll | 8944.1 Ops/sec |
I'll explain what's being tested in the provided benchmark.
The test compares two methods to select HTML elements with a specific class name: getElementsByClassName
and querySelectorAll
.
getElementsByClassName
This method returns a live HTMLCollection of all elements whose class attribute contains the specified value. The collection is ordered by the ordinal position of the elements in the document.
Pros:
querySelectorAll
because it doesn't require a single CSS selector expression.Cons:
querySelectorAll
This method returns a NodeList of all elements that match the specified CSS selector. The selector is evaluated from left to right, and the first argument (if present) determines the type of elements to return.
Pros:
getElementsByClassName
because it uses a more efficient algorithm to evaluate the CSS selector.Cons:
In this benchmark, the test creates 10,000 table rows with alternating classes, and then measures the time it takes to execute each method. The results show that querySelectorAll
is generally faster than getElementsByClassName
, especially for modern browsers like Firefox.
Note: The use of tableTest.rows[0].cells[0].textContent = found.length;
at the end of each benchmark definition is used to measure the execution time of each method, as it simply writes the length of the result array to a cell's text content.