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();
for (let i = 0; i < array.length; i++) {
array[i].r = array[i].a + array[i].b;
}
sum = x => x.r = x.a + x.b;
array.forEach(sum);
for (let x of array) {
x.r = x.a + x.b;
}
const result = [];
for (let x of array) {
result.push(x.a + x.b);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
for..of with reassign | |
for..of with no reassign |
Test name | Executions per second |
---|---|
for | 165.1 Ops/sec |
foreach | 60.7 Ops/sec |
for..of with reassign | 90.2 Ops/sec |
for..of with no reassign | 41.9 Ops/sec |
The benchmark in question evaluates the performance of different looping constructs in JavaScript: the traditional for
loop, the forEach
method, and the for..of
loop. The goal is to compare how quickly these constructs can sum the values of properties from an array of objects.
Traditional for
Loop
for (let i = 0; i < array.length; i++) {
array[i].r = array[i].a + array[i].b;
}
forEach
Method
sum = x => x.r = x.a + x.b;
array.forEach(sum);
for
loop due to additional overhead (function calls).for..of
Loop with Reassignment
for (let x of array) {
x.r = x.a + x.b;
}
for
loop.for
loop.for
loop in terms of speed.for..of
Loop with No Reassignment
const result = [];
for (let x of array) {
result.push(x.a + x.b);
}
for..of
loop.result
).Readability vs. Performance: While the forEach
and for..of
loops offer more readable syntax, they come at a cost in performance when compared to the traditional for
loop. This can be crucial in performance-critical applications.
Use Cases: Depending on the context—whether you require readability or whether you are working with performance-sensitive code—might dictate your choice of loop.
Modern JavaScript: The for..of
loop is an ES6 feature and is generally well-supported in modern environments, while the forEach
method is also commonly used in functional programming patterns.
While Loop: A traditional while
loop could also be utilized for similar functionality, but it would require explicit management of the loop variable, which can lead to complexity or errors if not handled properly.
Map Method: If transformation of each element is required without causing side effects, the .map()
function may be a viable alternative, effectively providing a new array based on a transformation of each element.
Reduce Method: The .reduce()
method can also sum the values, though it introduces a more functional style and could be less intuitive for operations where side effects (mutating the original array) are required.
In summary, this benchmark effectively illustrates the performance differences between various iteration approaches in JavaScript, highlighting trade-offs in terms of performance, readability, and suitability for specific tasks.