var arr = [];
for (var i = 0; i < 12345; i++) {
arr[i] = i;
}
function someFn(i) {
return (i * 3 * 8 / 1200 * 0.002 / 40 * 0.2);
}
var sumForEach = 0,
sumReduce = 0,
sumMap = 0,
sumFilter = 0,
sumFor = 0,
sumForOf =0;
arr.forEach(item => sumForEach += someFn(item));
sumReduce = arr.reduce((lastValue, item) => {
return sumReduce += someFn(item);
});
arr.map(item => (sumMap += someFn(item)));
arr.filter(item => (sumFilter += someFn(item)));
for (var j = 0; j < arr.length; j++) {
sumFor += arr[j];
}
for (let a of arr) {
sumForOf += a;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
forEach | |
reduce | |
map | |
filter | |
for | |
forof |
Test name | Executions per second |
---|---|
forEach | 234.4 Ops/sec |
reduce | 222.7 Ops/sec |
map | 212.5 Ops/sec |
filter | 225.5 Ops/sec |
for | 203.3 Ops/sec |
forof | 342.5 Ops/sec |
Let's dive into the Benchmark Definition and analyze what's being tested.
The benchmark measures the performance of various JavaScript iteration methods: forEach
, reduce
, map
, filter
, and for
(including for-of
). The test case creates an array of 12,345 elements, populated with integers from 0 to 11,444. Each iteration method is used to calculate a sum by applying the same function (someFn
) to each element in the array.
Here's a brief explanation of each approach:
forEach
: Iterates over the array using the forEach
method, calling the callback function for each element.reduce
: Accumulates the sum by reducing the array to a single value using the reduce
method, with an initial value of 0.map
: Creates a new array by mapping the original array's elements to a new value using the map
method, accumulating the sums in the process.filter
: Filters the array to only include elements that meet a condition (in this case, always true) and accumulates the sums in the filtered array.for
: Iterates over the array manually using a traditional for
loop, adding each element to the sum.Options compared:
The benchmark is comparing the performance of these five iteration methods on an array of 12,345 elements. The comparison aims to identify which method is most efficient in terms of execution time and memory usage.
Pros and Cons:
Library usage:
There is no explicit library used in the benchmark code. However, the map
method uses the Array.prototype.map()
method, which is a built-in JavaScript method.
Special JS feature or syntax:
for-of
loop (used in the "forof" test case) was introduced in ECMAScript 2015 (ES6). It provides a more concise and readable way to iterate over arrays without manual indexing.=>
) is also a modern JavaScript feature, introduced in ECMAScript 2015.Other alternatives:
To further improve performance or provide alternative iteration methods, other options could be explored, such as:
Array.prototype.forEach()
with a custom callback functionSymbol.iterator
method and next()
function