DEV Community

Discussion on: Stop mutating in map, reduce and forEach

Collapse
 
marcosvega91 profile image
Marco Moretti • Edited

Both examples are O(n) complexity so they should be almost similar. Only on large example you will see differences

Thread Thread
 
smeijer profile image
Stephan Meijer

True. I can't believe I missed that. Jacob Paris explains it dead simple in a tweet.

Looping once and doing three things on each item performs the same as doing one thing on each item but looping three times.

It's time I return to school.

Thread Thread
 
hiasltiasl profile image
Matthias Perktold

I also expected the filter+map version to be slower, not because of the extra loop, but because of the intermediate array that needs to be created. But maybe the browser can optimize it away.

Thread Thread
 
smeijer profile image
Stephan Meijer

I haven't profiled it on that level, so maybe there is a difference in memory usage. I honestly don't know. Browsers have changed quite a bit over the last few years. So I wouldn't be surprised if the intermediate array has been optimized away.

It would be interesting to compare the memory profiles though.