JavaScript Loops
If you have read some preformance tests on JavaScript loops, you may have heard that “while” is faster than “for”. However the question is how faster is “while”? Here are some results, but first let’s take a look on the JavaScript code.
The for experiment
console.time('for'); for (var i = 0; i < 10000000; i++) { i / 2; } console.timeEnd('for'); |
The while experiment
console.time('while'); var i = 0; while (i++ < 10000000) { i / 2; } console.timeEnd('while'); |
Note – these tests are performed and measured with Firebug on Firefox.
Results
It’s a fact, that you’ll get different results as many times as you run this snippet. It depends also on the enviroment and software/hardware specs. That is why I performed them 10 times and then I took the average value. Here are the values of my performance tests. Note that both for and while perform 10,000,000 iterations.
And the Winner Is
While is the winner with an average result of 83.5 milliseconds, while “for” result is 88 average milliseconds.
As the diagram bellow shows, the while loop is slightly faster. However we should be aware that these performance gains are significant for large number of iterations!
I think, if you have so diverse results (like 3 times slower “while” in second test), you have some process that disturbs normal testing. Anyway, you need to run not ten but ten million tests to be able to tell an average value properly.
The ‘extremely’ minor performance difference isn’t worth the uglier code.
First, I have to say that I find the results interesting. Thanks for the research.
That beeing said, I agree with Derrick. Moreover, I think that this should not even be an aspect considered in the optimizazion of the code. I think that there’s always space for algorithmic optimization dealing with computational complexity, first (something much more important to optimize).
Finally, nothing guarantees that this “optimization” will work on every interpreter or on different versions of the same interpreter.
Interesting, nevertheless.
Can you please try to replace i++ with ++i?
I ran 10 tests with 1 billion iterations and the average came out to be this
while: 14566.ms
for: 16297ms
(rounded figures)
so yea, while really is faster..
P.S change the font on textarea and inputs
This is really mind boggling. I had always believe “While” is the better OPTION but these test proves a probability issue(What’s the chance that the time you used the loop will be the best). Based on this result the best average performance is “While”.
However, The number of times “For” performed better is more than the number of times “While” did, especially with that significant “While” spike only occurred once out of ten attempts.
Now that tells me there is a greater chance of having a faster result with “For” than “While”. So while “while” is better on average, I’m now led to believe “For” is the better option.