function generateTestArray() {
const result = [];
for (let i = 0; i < 1000000; ++i) {
result.push(i);
}
return result;
}
window.array = generateTestArray();
const r = [];
for(const x of array) {
r.push(x);
}
array.map(x => x)
let r = 0;
for (const x of array) {
r += x;
}
array.reduce((p, x) => p + x, 0);
for(const x of array) {}
array.forEach(x => {})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
map comparison: for..of | |
map comparison: .map | |
reduce comparision: for..of | |
reduce comparision: .reduce | |
raw iteration: for..of | |
raw iteration: forEach |
Test name | Executions per second |
---|---|
map comparison: for..of | 87.6 Ops/sec |
map comparison: .map | 118.1 Ops/sec |
reduce comparision: for..of | 135.9 Ops/sec |
reduce comparision: .reduce | 109.0 Ops/sec |
raw iteration: for..of | 158.1 Ops/sec |
raw iteration: forEach | 233.1 Ops/sec |
Overview of the Benchmark
The provided benchmark compares the performance of three different approaches to iterate over an array:
for
loopforEach
methodmap
and reduce
methodsEach approach is compared with its equivalent version using for..of
, which is a newer syntax introduced in ECMAScript 2015.
Options Compared
The benchmark compares the following options:
for
loop (classic iteration)forEach
method (iterating over an array using the forEach
method)map
and reduce
methods (transforming and reducing an array using these methods)Pros and Cons of Each Approach
for
Loop
forEach
Method
for
loops or methods like map
and reduce
Map
and Reduce
Methods
Library Used
The benchmark uses a custom-generated array using JavaScript's for
loop to create an array of 1 million elements. This library is not external; instead, it's generated within the benchmark script itself.
Special JS Feature or Syntax
This benchmark does not explicitly use any special JavaScript features or syntax, such as async/await, Promises, or Web Workers. However, modern browsers' performance optimizations may influence the results of this benchmark.
Other Alternatives
In addition to the three approaches compared in the benchmark ( for
, forEach
, and map
/reduce
methods), other alternatives for iterating over arrays include:
for..of
loopArray.prototype.forEach.call()
method (in older browsers that don't support for...of
)index
variables or bitwise operators