var arr = new Array(1000000).fill(0).map((x, i) => i + 10);
function sumFn(acc, x) { return acc + x};
let sum = 0;
for (let x of arr) sum += x;
let sum = 0;
arr.forEach(x => { sum += x })
let sum = 0;
for(let i = 0; i < arr.length; i++) sum += arr[i];
const sum = arr.reduce(sumFn, 0)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for of | |
forEach | |
for | |
reduce |
Test name | Executions per second |
---|---|
for | 5.7 Ops/sec |
forEach | 48.6 Ops/sec |
for of | 736.2 Ops/sec |
reduce | 53.0 Ops/sec |
Let's break down what's being tested in this benchmark.
The benchmark is comparing the performance of four different approaches to calculate the sum of an array:
forEach
for
loopfor...of
loopreduce()
methodOptions Comparison
Here's a brief overview of each approach and their pros and cons:
forEach
, but with a few key differences.Other Considerations
forEach
and for...of
loops are similar in terms of performance, as they both iterate over the array without manual indexing. However, the for...of
loop might have a slight edge due to its native support in modern browsers.for
loop is likely to be the slowest option due to the need for manual indexing and potential optimization overhead.Library and Special JS Features
In this benchmark, there are no libraries used explicitly. However, it's worth noting that some of these approaches might rely on underlying library or framework optimizations (e.g., reduce()
).
No special JS features are mentioned in this benchmark.
Alternatives
If you're interested in exploring alternative approaches for summing up an array, here are a few options:
Array.prototype.every()
method instead of forEach
, which can provide similar performance benefits.Keep in mind that these alternatives might require significant changes to your codebase and may not provide a direct performance benefit compared to the original forEach
, for
, for...of
, and reduce()
approaches.