Which for-loop is the fastest in JavaScript?

siddiqus

Sabbir Siddiqui

Posted on December 25, 2022

Which for-loop is the fastest in JavaScript?

I was curious to see how fast loops perform in JS after seeing a similar post for C#, so I wrote a quick script to check.

Image description

For this test, I tried four different for-loop syntaxes, where each loop was simply incrementing a counter variable 10^8 times, and each loop ran five times to get an average time. Here are the results:

  • for-of: 1616.2 milliseconds
  • forEach: 1488.6 milliseconds
  • for loop (with index): 282.4 milliseconds
  • for loop (with cached array length): 278.8 milliseconds

Interestingly, for very small arrays (< 10^3 elements) it does not really make a difference. However, for 10^3 to 10^6 size, the result is a bit surprising.

Results for 1000 iterations:



{
  "forOf": 0.2,
  "forLoop": 0,
  "forEach": 0,
  "forLoopCached": 0
}


Enter fullscreen mode Exit fullscreen mode

Results for 100,000 iterations:



{
  "forOf": 5.4,
  "forLoop": 2,
  "forEach": 0.4,
  "forLoopCached": 0.6
}


Enter fullscreen mode Exit fullscreen mode

So when it comes to <10^6 arrays, the classic forEach seems to be just fine.

I personally used to use the for-of (slowest) syntax because it seemed like the easiest one, well now we know which one I'm going to start using!

Here is the script: https://github.com/siddiqus/useful-scripts/blob/master/for-loop-benchmark.js

P.S. Happy Holidays everyone!

💖 💪 🙅 🚩
siddiqus
Sabbir Siddiqui

Posted on December 25, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

Which for-loop is the fastest in JavaScript?