<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="style.min.css" type="text/css">
<link rel="stylesheet" href="style.min.css" type="text/css">
<link rel="stylesheet" href="style.min.css" type="text/css">
<link rel="stylesheet" href="style.min.css" type="text/css">
<link rel="stylesheet" href="style.min.css" type="text/css">
var linkEls = document.querySelectorAll('link[href*=".min.css"]');
[].forEach.call(linkEls,function(el){});
$('link[href*=".min.css"]').each(function(){});
var linkEls = document.querySelectorAll('link[href*=".min.css"]');
for (let link of linkEls){
link == link
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
forEach (Native) | |
each (jQuery) | |
for-of |
Test name | Executions per second |
---|---|
forEach (Native) | 326189.2 Ops/sec |
each (jQuery) | 197527.9 Ops/sec |
for-of | 333460.9 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Definition
The benchmark is comparing three different approaches to iterate over an array of elements:
forEach
: Using the native JavaScript forEach
method, which calls a callback function for each element in the array..each
: Using the jQuery library's .each
method, which also iterates over an array of elements and calls a callback function for each one.for-of
loop: Using the new for-of
loop syntax introduced in ECMAScript 2015, which allows iterating directly over arrays without using forEach
or indexing.Pros and Cons of Each Approach
forEach
:.each
:for-of
loop:Library and Syntax
The benchmark uses jQuery for the .each
method. The forEach
method is native JavaScript, while the for-of
loop is a modern syntax introduced in ECMAScript 2015.
Special JS Feature or Syntax
None of these examples use any special JavaScript features or syntax beyond what's already mentioned.
Other Alternatives
If you want to test other iteration methods, here are some alternatives:
For example, you could add a fourth test case using the reduce
method:
"Benchmark Definition": "var sum = 0;\r\nlinkEls.forEach(function(el) {\r\n sum += parseInt(el.href);\r\n});\r\nconsole.log(sum);"
This would compare the performance of the forEach
, .each
, and for-of
loops to the reduce
method.