<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.js'></script>
<content id="demo">Hello World!</content>
let components = '';
for (let i=0; i<10000; i+=1) {
components += '<div class="component" data-component="component' + i + '">Content ' + i + '</div>'
}
document.getElementById("demo").innerHTML = components;
let components = document.querySelector('[data-component]');
let components = $('[data-component]');
let components = document.querySelector('.component');
let components = $('.component');
let components = document.querySelector('div');
let components = $('div');
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
querySelectorAll by Attribute | |
jQuery selector by Attribute | |
querySelectorAll by Class | |
jQuery selector by Class | |
querySelectorAll by Element | |
jQuery selector by Element |
Test name | Executions per second |
---|---|
querySelectorAll by Attribute | 6625330.0 Ops/sec |
jQuery selector by Attribute | 6079.4 Ops/sec |
querySelectorAll by Class | 7264587.5 Ops/sec |
jQuery selector by Class | 15130.0 Ops/sec |
querySelectorAll by Element | 7236082.0 Ops/sec |
jQuery selector by Element | 15294.1 Ops/sec |
Let's dive into the explanation of the provided benchmark.
Overview
The benchmark compares the performance of two JavaScript libraries: querySelector
and jQuery, for selecting elements in HTML documents. The tests focus on four scenarios:
Options Compared
Two options are compared:
querySelector
function, using jQuery's syntax.Pros and Cons of each approach
querySelector
Pros:
Cons:
jQuery selector
Pros:
querySelector
.Cons:
Other considerations
The benchmark prepares a large HTML document with 10,000 elements, each with a unique class or attribute. The script preparation code generates this HTML document and appends it to an element with the id "demo".
Libraries used
The benchmark uses jQuery version 3.3.1.
Special JS feature or syntax
None mentioned in this benchmark.
Benchmark preparation code explanation
The script preparation code generates a large HTML document with 10,000 elements using the for
loop and string concatenation:
let components = '';
for (let i=0; i<10000; i+=1) {
components += '<div class=\"component\" data-component="component' + i + '">Content ' + i + '</div>';
}
document.getElementById("demo").innerHTML = components;
This code creates a large HTML document with 10,000 elements and appends it to an element with the id "demo".
Alternatives
If you need to compare the performance of other JavaScript libraries or functions for selecting elements, consider using:
querySelectorAll
, querySelector
, or getElementsByTagName
to select elements.Keep in mind that each approach has its strengths and weaknesses, and the choice of which one to use depends on your specific use case and requirements.