const items = Array.from({length: 1000}, () => Math.floor(Math.random() * 40));
let index = 0;
items.forEach(i => index += items[i]);
const items = Array.from({length: 1000}, () => Math.floor(Math.random() * 40));
let index = 0;
for (let i in items) index += items[i];
const items = Array.from({length: 1000}, () => Math.floor(Math.random() * 40));
let index = 0;
for (let i of items) index += i;
const items = Array.from({length: 1000}, () => Math.floor(Math.random() * 40));
let index = 0;
for(let i = 0; i < items.length; ++i) index += items[i];
const items = Array.from({length: 1000}, () => Math.floor(Math.random() * 40));
let index = 0;
let i = items.length;
while (i--) index += items[i];
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for-in | |
for-of | |
for | |
optimized-for |
Test name | Executions per second |
---|---|
foreach | 29044.2 Ops/sec |
for-in | 24133.0 Ops/sec |
for-of | 36487.3 Ops/sec |
for | 36439.2 Ops/sec |
optimized-for | 36760.9 Ops/sec |
The benchmark you've provided is designed to compare various JavaScript loop constructs in terms of their performance when iterating over an array. The benchmarks test five different methods of summing random numbers, which are generated using Math.random()
, from an array of 1000 elements.
for-each Loop (foreach
):
items.forEach(i => index += items[i]);
Array.prototype.forEach
method to iterate through the array.for-in Loop (for-in
):
for (let i in items) index += items[i];
for-of Loop (for-of
):
for (let i of items) index += i;
for-of
loop is designed for iterating over iterable objects (like arrays).Traditional for Loop (for
):
for(let i = 0; i < items.length; ++i) index += items[i];
for-of
and forEach
, although many developers find it intuitive.Optimized for Loop (optimized-for
):
let i = items.length;
while (i--) index += items[i];
In the latest benchmark results, the optimized-for
loop achieved the highest performance with 36,760 executions per second, followed closely by the for-of
loop (36,487) and the traditional for
loop (36,439). The forEach
loop had a significantly lower performance at 29,044 executions per second, while the for-in
loop performed the poorest with 24,132 executions per second.
When choosing the right loop construct, consider your specific use case:
for-of
loop is recommended for its balance of readability and performance.forEach
can enhance readability in simple cases, but avoid it when performance is critical, especially in large datasets.for-in
loop should generally be avoided for arrays due to its propensity to traverse inherited properties.Ultimately, the choice of loop structure can depend on your specific needs for clarity, performance, and functionality, along with personal or team conventions.