function generateTestArray() {
const result = [];
for (let i = 0; i < 1000000; ++i) {
result.push({
a: i,
b: i / 2,
r: 0,
});
}
return result;
}
const a = generateTestArray();
a.forEach( b => b*2 );
const a = generateTestArray();
for ( let b of a) {
b=b*2;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
forEach | |
for of |
Test name | Executions per second |
---|---|
forEach | 5.8 Ops/sec |
for of | 5.6 Ops/sec |
Let's break down the provided JSON and explain what is tested in the microbenchmark.
Benchmark Purpose
The benchmark compares the performance of two approaches: forEach
and for...of
. The test creates an array of 1,000,000 objects and then iterates over it using both methods. In each iteration, a specific operation is performed on each object (in this case, multiplying the b
value by 2).
Options Compared
The two options compared are:
forEach
: A traditional, callback-based loop that accepts a function as an argument.for...of
: A newer, more modern looping construct that iterates over arrays and other iterable objects.Pros and Cons of Each Approach
forEach
:for...of
due to the overhead of callback functions.for...of
:forEach
.Library and Syntax
None of the test cases use any external libraries. The syntax used is standard JavaScript (ES6+).
Special JS Features or Syntax
There are no special features or syntaxes mentioned in this benchmark.
Other Alternatives
In addition to forEach
and for...of
, other looping constructs that could be compared in a similar benchmark might include:
while
loopsdo-while
loopsmap()
, filter()
, and reduce()
methods (which are related to forEach
but offer more functional programming features)In terms of modern alternatives, the comparison between forEach
and for...of
is quite straightforward. However, if you were to expand this benchmark to compare other looping constructs or explore more advanced JavaScript features, the options would increase.
For example, if you wanted to compare the performance of different array methods like map()
, filter()
, and reduce()
against traditional loops (like forEach
), that could be an interesting exploration. Alternatively, comparing these constructs against more modern alternatives like WebAssembly or other JavaScript engines would provide a deeper insight into the nuances of JavaScript performance.