var arr = [];
for (var i = 0; i < 1000; i++) {
arr[i] = i;
}
function someFn(i) {
return i * 3 * 8;
}
arr.forEach(function (item){
someFn(item);
})
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
arr.map(item => someFn(item))
arr.forEach(item => someFn(item))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
map | |
foreach with arrow as well |
Test name | Executions per second |
---|---|
foreach | 169421.2 Ops/sec |
for | 780140.7 Ops/sec |
map | 69895.9 Ops/sec |
foreach with arrow as well | 141465.5 Ops/sec |
Let's break down the benchmark and explain what is being tested.
Benchmark Overview
The benchmark measures the performance of three different approaches to iterate over an array in JavaScript:
forEach
method, which is a built-in array method that calls a provided function once for each element in the array.map
method, which returns a new array with the results of applying a provided function to each element in the original array.Options Compared
The benchmark compares the performance of these three approaches:
forEach
method, which is a built-in array method that calls a provided function once for each element in the array. There are two variations:map
method, which returns a new array with the results of applying a provided function to each element in the original array.Pros and Cons
Here are some pros and cons of each approach:
Library and Special JS Features
There is no library used in this benchmark. However, it does use the following special JavaScript features:
forEach
approach.forEach
and map
methods are built-in to the JavaScript language.Other Alternatives
Other alternatives to iterate over arrays in JavaScript include:
for...of
loop (introduced in ECMAScript 2015)Array.prototype.reduce()
Array.prototype.every()
or Array.prototype.some()
Note that each of these alternatives has its own trade-offs and use cases, and may not always be the best choice for every situation.