DEV Community

Sabbir Siddiqui
Sabbir Siddiqui

Posted on

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!

Top comments (3)

Collapse
 
binarytreecode profile image
BinaryTreeCode

Modifique (... con gpt) un poco el código y medio estos resultados:

Image description

Collapse
 
noriste profile image
Stefano Magni

Out of curiosity: did you run them in Node.js or in the browser? Thanks for sharing, by the way 😊

Collapse
 
alexeyplodenko profile image
Alexey Plodenko

The Chrome browser gives similar results to the shown in the article - measurethat.net/Benchmarks/Show/18...