TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Follow publication

Javascript performance test - for vs for each vs (map, reduce, filter, find).

Deepak Gupta
TDS Archive
Published in
3 min readMay 9, 2018
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 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

  1. They have a call back to execute so that acts as an overhead.
  2. 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:

  1. Code readability and maintainability
  2. Ease code

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

TDS Archive
TDS Archive

Published in TDS Archive

An archive of data science, data analytics, data engineering, machine learning, and artificial intelligence writing from the former Towards Data Science Medium publication.

Deepak Gupta
Deepak Gupta

Written by Deepak Gupta

COO @Steer Protocol| Write about Blockchain & Javascript | Take it easy

Responses (21)

Write a response