DEV Community

Sabbir Siddiqui
Sabbir Siddiqui

Posted on

6

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!

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

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...

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay