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))
arr.forEach( (v)=> v*3*8 );
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
map | |
foreach2 |
Test name | Executions per second |
---|---|
foreach | 86274.7 Ops/sec |
for | 6847.3 Ops/sec |
map | 12559.7 Ops/sec |
foreach2 | 1133933.5 Ops/sec |
Let's break down what's being tested in the provided JSON.
Benchmark Definition
The benchmark is designed to compare the performance of three different ways to iterate over an array and apply a function to each element:
arr.forEach(someFn)
: This uses the forEach
method, which executes the provided callback function once for each element in the array.for (var i = 0, len = arr.length; i < len; i++) { someFn(arr[i]); }
: This is a traditional for
loop that iterates over the array elements using their indices.arr.map(item => someFn(item))
: This uses the map
method, which creates a new array by applying the provided callback function to each element in the original array.Options compared
The benchmark compares the performance of these three approaches:
forEach
for
loopmap
Pros and Cons
Here are some pros and cons for each approach:
forEach
:for
loop:map
:Library and Special JS feature
There is no library mentioned in the benchmark definition or the test cases provided. However, if you were to use libraries like Lodash or Ramda, they might provide alternative implementations for these functions (e.g., lodash.forEach
, ramda.map
).
Special JS features
There are no special JavaScript features (like async/await, generators, or promises) used in the benchmark definition.