One thing I’ve heard a couple of times in either a trac ticket or in a forum thread is that we should all switch over to a decrement-style loop. Why? Simply because it’s faster. (We’ll ignore the time it takes to realize that you can actually loop down to zero.)
I’ve wondered if it really made a difference so in two of my favorite languages, I did a couple of tests. In Java, I wrote a program to loop up and down one billion times and then take the average over ten runs of that. Javascript would only freeze when I tried to loop with a billion, so I used 100000 instead, but I raised the number of times I took the average. It’s hard to be fair when comparing, but in all honestly, we’re not comparing Java to Javascript, we’re comparing each to themselves.
Without further ado, let’s see some results!
Let’s talk about the Javascript version, first. It had the strangest results. What I found was that when I ran the tests in Firefox 3.5RC1, I normally got close results with decrement being slightly faster. When I racked up the number of trials, the difference between the averages went down, but even then, decrement was always slightly faster. But then I ran the tests in Google Chrome. I often found a 15 millisecond difference between the two averages. Sometimes decrement wasn’t the fastest, but it usually was, and by at least 15 milliseconds. So, in javascript, with a regular loop (nothing fancy about, no frameworks, no prototype mangling) took decrements about 28-32 milliseconds while increments took 28-56 milliseconds. Neat, huh?
Now, how about Java? Because I used significantly higher numbers, I thought the averages would be better. What I found was that, quite often, the averages were the same! Now, this wasn’t always true. Sometimes the decrement would be faster by about 25-50 milliseconds faster. Java wasn’t that interesting, but its safe to say that the decrement loop is slightly faster.
My results are dependant on my computer’s CPU, which is a dual core Athlon 2.40 GHz. The java tests are dependant on the JRE I’m running (6.14) and the javascript tests are dependant on Firefox 3.5RC1 and Chrome 3.0.139.
You can run my tests if you’d life, here’s the java and javascript tests.