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 (var i of arr) {
someFn(arr[i]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
map | |
for of |
Test name | Executions per second |
---|---|
foreach | 1146698.6 Ops/sec |
for | 462643.6 Ops/sec |
map | 410604.4 Ops/sec |
for of | 395135.2 Ops/sec |
Let's break down the provided benchmark definition and test cases.
Benchmark Definition
The benchmark defines four different approaches to iterate over an array:
arr.forEach(someFn)
: Uses the forEach
method to iterate over the array, calling someFn
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 and calling someFn
.arr.map(item => someFn(item))
: Uses the map
method to create a new array with transformed elements, where each transformation is applied using someFn
.for (var i of arr) { someFn(arr[i]); }
: Uses an iterative syntax introduced in ECMAScript 2015 (for...of
) to iterate over the array, accessing each element and calling someFn
.Library
None of the test cases use any external libraries.
Special JS feature or syntax
The test case using for...of
syntax is a special feature introduced in ECMAScript 2015. This syntax allows iterating over arrays without needing an explicit index variable.
Benchmark Comparison
The four approaches have different performance characteristics:
forEach
method, which is implemented in native code and optimized for performance.Pros and Cons
Here's a brief summary of each approach:
forEach
:Other Alternatives
Alternative approaches could include:
reduce()
or other aggregate methods instead of iterating over the array.However, these alternatives may not be as straightforward to implement and maintain as the four approaches used in this benchmark.