Array.reduce() VS Nested Array.forEach() Run Time Comparison in Node.JS/JavaScript

Hanjun Chen
Aug 25, 2017 · 1 min read

I would say nested foreach is faster. But let’s do a test. First we set up an array of 90000 members, and an new array for hosting the flattened array:

Now let’s do a speed test for Array.reduce():

I ran the code about for 10 times and these are the outputs (in milliseconds):

15610, 15554, 16042, 16264, 15781, 15776, 15636, 15945, 15876, 15699

When I change it to nested foreach loop:

the outputs are:

36, 37, 39, 34, 41, 39, 38, 36, 41, 34

The outputs are similar when I use nested iterators:

It seems to me that nested foreach is much faster.

)
Hanjun Chen

Written by

Software developer with .Net, Node.js, AWS and marketing background.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade