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.
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
}
Results for 100,000 iterations:
{
"forOf": 5.4,
"forLoop": 2,
"forEach": 0.4,
"forLoopCached": 0.6
}
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)
Modifique (... con gpt) un poco el código y medio estos resultados:
Out of curiosity: did you run them in Node.js or in the browser? Thanks for sharing, by the way 😊
The Chrome browser gives similar results to the shown in the article - measurethat.net/Benchmarks/Show/18...