<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
$("div").each(function(i){
$(this).text("a");
});
[document.querySelectorAll("div")].map(e=>{
e.innerText = "a";
});
let divs = [document.querySelectorAll("div")];
for(let i=0;i<divs.length;i++){
divs[i].innerText = "a";
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
JQ | |
Vanilla | |
Vanilla No Map |
Test name | Executions per second |
---|---|
JQ | 66230.0 Ops/sec |
Vanilla | 128331.1 Ops/sec |
Vanilla No Map | 127528.1 Ops/sec |
Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided benchmark definition json represents a comparison between jQuery (JQuery) and vanilla JavaScript for a specific use case: updating the text content of multiple HTML elements.
Script Preparation Code
The script preparation code includes a reference to jQuery 3.6.1, which is loaded via a CDN link. This ensures that all tests run with the same version of jQuery. The code also creates four empty HTML div
elements, which will be used as targets for the benchmarking process.
Individual Test Cases
There are three individual test cases:
$("div").each(function(i){\r\n $(this).text("a");\r\n});
.each()
method to iterate over the elements with the class div
and updates their text content to "a"
.[...document.querySelectorAll("div")].map(e=>{\r\n\te.innerText = "a";\r\n});
Array.prototype.map()
method to create a new array of elements with the class div
, updates their text content to "a"
using the innerText
property.let divs = [...document.querySelectorAll("div")];\r\nfor(let i=0;i<divs.length;i++){\r\n\tdivs[i].innerText = "a";\r\n}
map()
, it uses a traditional for
loop to iterate over the elements and update their text content.Options Compared
The three test cases compare the following options:
.each()
versus using a traditional for
loop.map()
versus not using map()
.Pros and Cons of Each Approach
.each()
for large datasets, as it uses a more optimized algorithm for creating arrays.
Cons:.each()
method.map()
for large datasets.Library Used
In this benchmark, jQuery is used to provide a convenient way to iterate over elements with a class selector. The library itself is loaded via a CDN link.
Special JS Feature or Syntax
None of the test cases use any special JavaScript features or syntax that are not commonly used in vanilla JavaScript.
Other Alternatives
If you were to create your own benchmarking tool, you might consider using alternative libraries or approaches, such as:
Keep in mind that the choice of approach will depend on your specific use case and requirements. MeasureThat.net provides a convenient and easy-to-use interface for comparing different approaches, but you may need to adapt or modify the code to suit your own needs.