DEV Community

Abhishek Gowda
Abhishek Gowda

Posted on

Array.Map vs For...loop

I was solving a problem and saw when I used Array.map the execution was lagging a bit. And thought to switch to using for...loop, as I was not doing any complicated calculation within map callback.

This is the sample benchmark data I used

6,1,4,5,3,9,0,1,9,5,1,8,6,7,0,5,5,4,4
Enter fullscreen mode Exit fullscreen mode

And I did not do anything fancy, just pushed it to an array, similar to map where is returns us a new array.

Map and for loop beanching marking

Compared it using JS Perf and saw that for..loop is ~25 times faster than map.

I would not be switching to for..loop because of this, a good to know when there is a slow down in the application.

Top comments (2)

Collapse
 
nevodavid profile image
Nevo David

Pretty cool seeing you actually testing stuff in real code. Makes me wanna check if half the stuff I use daily is slower than I think.

Collapse
 
nathan_tarbert profile image
Nathan Tarbert

Yeah, knowing both tricks helps a ton. I always reach for what keeps my brain happy unless the speed drop is unbearable.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.