var arr = [];
for (let j=0; j < 1000000; j++ ) {
arr.push(j);
}
const r = arr.reduce( (p,c) => p+c, 0);
let r=0; for (v of arr) { r+=v; }
let r = 0; const l = arr.length; for (var i=0; i < l; i++ ) { r += arr[i]; }
let r = 0; arr.forEach( (v) => r += v );
let r=0; for (const v of arr) { r+=v; }
let r = 0, i=0; const l = arr.length; for (;i < l;) { r += arr[i++]; }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Reduce | |
for..of | |
for | |
foreach | |
for..of with const | |
for again |
Test name | Executions per second |
---|---|
Reduce | 50.7 Ops/sec |
for..of | 1.9 Ops/sec |
for | 8.3 Ops/sec |
foreach | 31.6 Ops/sec |
for..of with const | 751.6 Ops/sec |
for again | 8.2 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Preparation Code
The script preparation code creates an array arr
with 1,000,000 elements, each containing a sequential number from 0 to 999,999. This is done using a for
loop that pushes each number onto the array.
Test Cases
The benchmark consists of six test cases, each measuring the performance of a different JavaScript iteration method:
Reduce
: Uses the reduce()
method to sum up all elements in the array.for..of with const
: Uses a for...of
loop with const
declaration to iterate over the array and sum up its elements.foreach
: Uses the forEach()
method to iterate over the array and sum up its elements.for
: Uses a traditional for
loop to iterate over the array and sum up its elements.for again
: Similar to the previous one, but uses an index variable (i
) instead of a direct reference to the element.for..of
: Another for...of
loop without const
, used for comparison.Library Usage
None of these test cases explicitly use any libraries or external dependencies.
JS Features/Syntax
The only notable feature is the use of const
declaration in some test cases (for..of with const
and another for...of
). This is a relatively modern JavaScript feature that declares variables as constant, ensuring they cannot be reassigned. Its usage helps prevent potential performance issues by avoiding unnecessary reassignments.
Options Compared
The benchmark compares the performance of six different iteration methods:
for
loops, providing better performance and readability.for
loop with an additional index variable (i
).for...of with const
, but without declaring variables as constant.Pros and Cons
Here's a brief summary:
for
loops. It also ensures variables are not reassigned, which can prevent performance issues in some cases.for...of
, but may have additional overhead due to its method call.for
loops with an additional index variable. It may not offer significant performance benefits over the other options.Other Alternatives
Some alternatives to these iteration methods include:
Array.prototype.map()
or Array.prototype.every()
to achieve similar results.Keep in mind that the best approach will depend on the specific use case and requirements.