Photo by Alex Holyoake on Unsplash
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 object and doing some operation via for loop/ foreach / javascript functions and observing the time it take 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.
// calculated the sum of upVotesconst 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 .
Map/Reduce/Filter/Find are slow because of many reason, some of them are
I found a lib. that reimplement several common builtin native JavaScript functions.
But the choice of usage depend on not just the performance alone, there are more factors to be considered, some of them are:
Personally I love map, reduce, filter, find and I am using them from a long time. They helped me write clean, precise, fast and to the point code which align with my thought process. I use for loop when i have no choice left. As far as optimisation is concerned, map/reduce/filter/find replacement should be the the last option or not an option depending upon what level of optimisation is required.
Note: If you’re using loops, always use them idiomatically since compilers are now smart enough to correctly optimize idiomatic loops
Update: Here you can find the result for large data set and heavy computation.
Please consider entering your email here if you’d like to be added to my email list and follow me on medium to read more article on javascript and on github to see my crazy code. If anything is not clear or you want to point out something, please comment down below.
THANK YOU!