Posted by masis on Wed Jun 15 2022
As we know, JavaScript / TypeScript has a set of powerful array utility functions including forEach()
, map()
, reduce()
 and so on. Those utility functions greatly improve our productivity in array operations by using functional programming paradigm and they are clearer to read and easier to understand.
I believe the above refactored codes also intend to achieve a better readability and maintainability, but the member of rxjs library rejects the changes and claim that it is.
foreach() for for loop
const list = Array(20000000).fill(0);
const list1 = [];
const list2 = [];
// 20 millions records with a for loop
console.time("for loop");
for (let i = 0; i < list.length; i++) {
list1[i] = i + 1;
}
console.timeEnd("for loop");
// 20 millions records with forEach()
console.time("forEach()");
list.forEach((_, i) => {
list2[i] = i + 1;
});
console.timeEnd("forEach()");
// Sanity check if the list1 and list2 are with the same calculation results
console.log(
list1.every((item, index) => item === list2[index]) &&
list1.length === list2.length
);
I ran the code 5 times and got the following results.
 | for | foreach() |
1 | 408.801ms | 629.787ms |
2 | 410.799ms | 629.338ms |
3 | 409.691ms | 631.505ms |
4 | 390.361ms | 612.205ms |
5 | 390.503ms | 618.609ms |
So the result is very clear that for
 loop performs better than forEach()
. Although there are 20 million records, the operations are simple, only value addition and assignment. What if the operations are complexer such as demonstrated in rxjs, every subscriber is notified and certain following actions are triggered? Just because foreach loop looks prettier does not make it better in terms of performance.