DEV Community

Discussion on: Possible ways of Iterating ARRAYS in JavaScript

Collapse
 
miketalbot profile image
Mike Talbot ⭐

Thanks for the article - it certainly does cover off all of the methods.

I'm just about to write on this subject myself - and having just been researching:

  • Firstly your first examples don't seem to line up e.g. (1) says its a for(;;) loop, but your example isn't - it's some kind of filter. There are a couple of others that are also not what the title says.

  • Secondly for(;;) loops are held to be fastest - and jsPerf and jsBench.me will tell you that. But run it in your own browser or codesandbox and you may be in for a surprise.

  • Thirdly - reading the length every iteration doesn't appear to make any difference, in fact it can be faster because modern browser Javascript engines optimise for it. They know that JS is single threaded and spot the pattern.

Collapse
 
iainfreestone profile image
Iain Freestone

Your third point is interesting I had wondered about this in the past. Off to look further into this!

Collapse
 
aashrithashiva29 profile image
Aashritha Shiva • Edited
  • I haven't checked the example issue... I have corrected it. Thanks for this :)
  • yeah, I have come to the conclusion after performing the test with performance.now(). But it was wrong. Yes "for loop is the fastest"
  • and caching length inside the loop is fine!!
  • jsPerf was great And to correct "for..of" is faster compared to for..in and forEach but indeed for is the fastest one over all others. Thanks for listing out these points.