Wednesday, March 27, 2024

JavaScript speed: forEach, .map, .reduce vs for, for..of

Performance of JavaScript .forEach, .map and .reduce vs for and for..of

Both for and for..of are 3.5 times faster than reduce. However, the loops are much more verbose.
.forEach is almost the same as for or for..of, only 3 times slower.

Here we just calculate the sum of a and b for the whole array:

return array.reduce((p, x) => p + x.a + x.b, 0);

Both for and for..of are 3.5 times faster than reduce. However, the loops are much more verbose:

let result = 0;for (const { a, b } of array) {   result += a + b;}return result;

No comments: