Introduction
Make loops go faster! Arg! :(
It's 2014 and JavaScript JIT compilers should have solved this a long time ago! RANT!!!!
So here's how we know for sure. We make a test. The results are quite perplexing...
Background
Not too many years ago, there were a few web posts about how do{}while(--i)
was faster that a standard for
loop. In addition, there was talk long ago about how ++i
is faster than i++
.
Using the Code
Open up Firefox's console (Ctrl-Shift-K), and paste the following code into Firefox's Scratchpad (Shift+F4), and you'll see what I'm talking about.
var iterations = 1000000;
var c = 0;
function operation(i) {
c += 1;
}
[
{
forloop1:
function () {
for (var i = 0; i < iterations; i++)
operation(i);
}
},
{
forloop2:
function () {
for (var i = 0; i < iterations; ++i)
operation(i);
}
},
{
dowhile:
function () {
var i = iterations;
do {
operation(i);
}
while (--i);
}
}
].forEach(function (test) {
var name;
for (var key in test)
name = key;
var t = test[key];
c = 0;
var time = (new Date()) .getTime();
t();
var elapsed = (new Date()) .getTime() - time;
console.log(name + ': ' + elapsed + ' ms');
});
Of course, you can use this simple test timer with other tests as well, but I've outlined the 3 contenders.
The end result should look something like this:
"forloop1: 450 ms" Scratchpad/1:40
"forloop2: 414 ms" Scratchpad/1:40
"dowhile: 230 ms" Scratchpad/1:40
Regardless of the iteration count you choose, the proportions come out consistently about the same and the results are clear.
Now if you change console.log
to alert
and embed this in a HTML page... The results are quite different. (You'll need to 10x the iterations at least.)
Apparently, when in an HTML page (tested Firefox and Internet Explorer) the JIT is active and the iterations are magnitudes faster. Also, it is hard to tell from multiple tests which loop type is actually faster because the results are about the same every time with a somewhat random deviation.
Conclusion :)
Hooray for JIT! I was a bit worried when Firefox's Scratchpad performed like 2007. :P But as seen here, browsers have lived up to their promises, and compiled JavaScript is not only much faster, but also optimized for you. :)
It's only when JavaScript is running in interpreted mode that you see for
loops take twice as long as do{}while(--i)
and ++i
being a bit faster than i++
.