function generateTestArray() {
const result = [];
for (let i = 0; i < 1000000; ++i) {
result.push({
a: i,
b: i / 2,
r: 0,
});
}
return result;
}
const array = generateTestArray();
array.forEach((x) => {
x.r = x.a + x.b;
});
const array = generateTestArray();
for (const obj of array) {
obj.r = obj.a + obj.b;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foeach | |
forof |
Test name | Executions per second |
---|---|
foeach | 26.9 Ops/sec |
forof | 40.5 Ops/sec |
I'd be happy to help you understand what's being tested in the provided JSON benchmark.
What is being tested?
The benchmark tests two different ways of iterating over an array in JavaScript: forEach
and for...of
. Both methods are used to update a property (r
) in each object within the array.
Options compared
The benchmark compares the performance of two approaches:
forEach
loop: This method iterates over the array using a traditional for
loop, but with a callback function that updates the r
property of each object.for...of
loop: This method uses a more modern syntax to iterate over the array, where you can directly access properties and perform operations on them.Pros and Cons
forEach
loop:for...of
loops due to the overhead of function calls.for...of
loop:Library/Utility used
In this benchmark, no external library is explicitly mentioned. However, the generateTestArray()
function uses a bit of magic to create an array of 1 million objects with specific properties (a
, b
, and r
). This function is likely included as part of the benchmark itself.
Special JavaScript feature/Syntax
The benchmark uses the for...of
loop, which is a relatively modern syntax introduced in ECMAScript 2015 (ES6). It's supported in most modern browsers and Node.js versions. If you're using an older environment, you might need to use a polyfill or transpile your code to support this syntax.
Other alternatives
If you want to optimize the forEach
loop, you could consider:
Set
or a Map
, instead of an array.For the for...of
loop, you could consider:
Array.from()
or a custom implementation.reduce()
or map()
, depending on your specific use case.