const array = [];
for (let i = 0; i < 1000000; ++i) {
result.push({
a: i,
b: i / 2,
});
}
const r = 0;
for (let i = 0; i < array.length; ++i) {
r += array[i].a + array[i].b;
}
array.reduce((p, x) => p + x.a + x.b, 0);
array.reduce((p, {a,b}) => p + a + b, 0);
let r = 0;
for (const x of array) {
r += x.a + x.b;
}
let r = 0;
for (const {a,b} of array) {
r += a + b;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
.reduce | |
.reduce (destructuring) | |
for..of (reduce) | |
for..of (reduce) (destructuring) |
Test name | Executions per second |
---|---|
for | 183367248.0 Ops/sec |
.reduce | 53378000.0 Ops/sec |
.reduce (destructuring) | 61994520.0 Ops/sec |
for..of (reduce) | 180358480.0 Ops/sec |
for..of (reduce) (destructuring) | 60718912.0 Ops/sec |
The benchmark you provided compares the performance of different methods for summing properties of objects within an array in JavaScript. The key methodologies tested in this benchmark are:
for
)reduce
Method (.reduce
)reduce
Method (.reduce (destructuring)
)for..of
)for..of (destructuring)
)For Loop:
const r = 0;
for (let i = 0; i < array.length; ++i) {
r += array[i].a + array[i].b;
}
Array's reduce
Method:
array.reduce((p, x) => p + x.a + x.b, 0);
Destructured reduce
Method:
array.reduce((p, {a,b}) => p + a + b, 0);
reduce
, can incur performance hits due to destructuring and function calls.For-Of Loop:
let r = 0;
for (const x of array) {
r += x.a + x.b;
}
Destructured For-Of Loop:
let r = 0;
for (const {a,b} of array) {
r += a + b;
}
Based on the latest benchmark results, the measurements of executions-per-second for each test case highlight the following observations:
.reduce
methods tend to score lower, likely due to the overhead of function invocations.for..of
) and traditional loops.reduce
or for..of
may be preferred.Other methods for similar tasks could include:
.map()
or .filter()
followed by reducing could yield more complex processing pipelines.In essence, the choice of which approach to use should account for specific project needs, data types, and performance requirements.