var arr = [];
for (var i = 0; i < 1000; i++) {
arr[i] = i;
}
function someFn(i) {
return i * 3 * 8;
}
arr.forEach(someFn)
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
arr.map(item => someFn(item))
for (const i of arr) {
someFn(i);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
map | |
for of |
Test name | Executions per second |
---|---|
foreach | 104520.0 Ops/sec |
for | 6433.6 Ops/sec |
map | 12188.8 Ops/sec |
for of | 12773.0 Ops/sec |
I'll break down the provided benchmark and explain what's being tested, the options compared, pros and cons of each approach, and other considerations.
Benchmark Definition
The benchmark compares four different ways to iterate over an array in JavaScript:
arr.forEach(someFn)
for (var i = 0; i < arr.length; i++) { someFn(arr[i]); }
arr.map(item => someFn(item))
for (const i of arr) { someFn(i); }
The benchmark is comparing these four approaches for a specific use case: applying the function someFn
to each element of an array, where someFn
multiplies its input by 3 and then by 8.
Library Used
There is no library explicitly mentioned in the provided code. However, it's worth noting that the map()
method uses a built-in JavaScript method, whereas the other approaches require manual iteration using loops.
Special JS Features/Syntax
The benchmark uses modern JavaScript features:
item => someFn(item)
): Introduced in ECMAScript 2015 (ES6)for...of
loop: Introduced in ECMAScript 2015 (ES6)Options Compared
Here's a brief overview of each option:
arr.forEach(someFn)
: Iterates over the array using the forEach()
method, which calls the provided function for each element.for (var i = 0; i < arr.length; i++) { someFn(arr[i]); }
: Uses a traditional for
loop to iterate over the array, accessing each element using its index.arr.map(item => someFn(item))
: Uses the map()
method to create a new array by applying the provided function to each element of the original array.for (const i of arr) { someFn(i); }
: Uses the for...of
loop to iterate over the array, which is more concise and expressive than traditional for
loops.Other Considerations
When choosing an iteration approach, consider factors such as:
Alternatives
Other iteration approaches you might consider include:
Array.prototype.reduce()
: Used for reducing an array to a single value or creating an accumulator.Array.prototype.every()
or Array.prototype.some()
: Used for testing conditions on each element of the array.Keep in mind that the performance differences between these approaches can be significant, especially when dealing with large datasets.