var
arr = Int32Array.from({ length: 1000 }, (_, i) => i),
fun = n => 3 * n >> 1,
res = 0;
const array = arr, len = arr.length;
for (var i = 0; i < len; res += fun(array[i++]));
console.log('for (;;):', res, res = 0);
const array = arr;
for (const i in array) res += fun(array[i]);
console.log('for (in):', res, res = 0);
for (const v of arr) res += fun(v);
console.log('for (of):', res, res = 0);
arr.forEach(v => res += fun(v));
console.log('forEach():', res, res = 0);
arr.map(v => res += fun(v));
console.log('map():', res, res = 0);
res = arr.reduce((a, v) => a + v);
console.log('reduce():', res, res = 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
regular for (;;) | |
for..in | |
for..of | |
forEach() | |
map() | |
reduce() |
Test name | Executions per second |
---|---|
regular for (;;) | 5094.0 Ops/sec |
for..in | 4120.9 Ops/sec |
for..of | 4992.3 Ops/sec |
forEach() | 4927.9 Ops/sec |
map() | 4624.0 Ops/sec |
reduce() | 55952.6 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The benchmark is designed to compare the performance of different ways to iterate over an array and calculate its sum. The script preparation code creates an array of 1000 integers, calculates the square of each element (using the fun
function), and sums up the results. The description mentions six approaches: for (;;)
, for..in
, for..of
, forEach()
, map()
, and reduce()
.
Test Cases
The benchmark consists of seven test cases, each representing one of the mentioned approaches:
for
loop that uses an index variable to iterate over the array.for...in
loop that iterates over the array's indices, using the in
keyword to access each element.for...of
loop that directly iterates over the array elements, without accessing an index variable.Array.prototype.forEach()
method is called on the array, passing a callback function to process each element.Array.prototype.map()
method is called on the array, passing a callback function to transform each element (in this case, squaring it).Array.prototype.reduce()
method is called on an initial value of 0, passing a callback function to accumulate the sum of the elements.Libraries and Features
forEach()
, map()
, and reduce()
are built-in methods of the Array prototype.Pros and Cons
Here's a brief overview of the pros and cons for each approach:
in
keyword to access elements, which involves a string conversion.for..in
, but may have minor performance variations depending on the engine.Other Alternatives
If you'd like to explore other approaches, consider:
array.prototype.forEach()
with a custom callback functionArray.prototype.reduce()
with a custom initial valueKeep in mind that the performance differences between these approaches may vary depending on the specific use case and engine.