Member-only story
Javascript performance test - for vs for each vs (map, reduce, filter, find).
We all know that for loop are faster than for each or javascript function since under the hood of javascript functions might be using for loops or something else which I’m not sure. I did a simple test with an array of objects and doing some operation via for loop/ for each / javascript functions and observing the time it takes to execute.
These results are from small examples and may vary as per the operation performed, the choice of execution env. and choice of VM.
1. Reduce vs for loop vs foreach
// calculated the sum of upVotes
const posts = [
{id: 1, upVotes: 2},
{id: 2, upVotes: 18},
{id: 3, upVotes: 1},
{id: 4, upVotes: 30},
{id: 5, upVotes: 50}
];let sum = 0;
console.time('reduce');
sum = posts.reduce((s, p)=> s+=p.upVotes,0);
console.timeEnd('reduce')sum = 0;
console.time('for loop');
for(let i=0; i<posts.length; i++) {
sum += posts[i].upVotes;
}
console.timeEnd('for loop');sum = 0;
console.time('for each');
posts.forEach(element => {
sum += element.upVotes;
});console.timeEnd('for each');
Note: Below is the list of results and code can be found here .
All the results clearly show that for loop are more proficient than for each than map/reduce/filter/find.
Map/Reduce/Filter/Find are slow because of many reasons, some of them are
- They have a call back to execute so that acts as an overhead.
- There are a lot of corner cases that javascript functions consider like getters, sparse array and checking arguments that are passed is an array or not which adds up to overhead.
I found a lib. that reimplement several common builtin native JavaScript functions.
But the choice of usage depends on not just the performance alone, there are more factors to be considered, some of them are:
- Code readability and maintainability
- Ease code