Update, 7/1/2009: Switched code blocks from manual coloring to an automatic syntax highlighter plugin.
Looking for JavaScript optimization tweaks, I encountered a claim that a decrementing do-while loop is faster than an incrementing for loop. I decided to do a quick-and-dirty test to see if there’s any clearly discernible difference. I wrote two scripts, each of which does the exact same thing: create 100,000 DIVs and append them to the body of the page. First we have the standard for version, then the do-while format that the site claimed was superior.
Version 1:
for (var i = 0, d; i < 100000; i++) {
d = document.createElement("div");
d.innerHTML = "DIV #" + i + "";
document.body.appendChild(d);
}
Version 2:
var j = 0;
do {
var i = 100000 - j,
d = document.createElement("div");
d.innerHTML = "DIV #" + i + "";
document.body.appendChild(d);
} while (--j);
Note that the do-while has an extra line to set a variable i that will increment just as i does in the for loop, thus we get the same result of DIVs numbered 0-99,999. But what if the direction doesn’t matter? What if going backwards and numbering the DIVs from high to low is acceptable, or even what we actually want? The do-while proponent cited in support of his claim that computers are simply faster at counting down than they are at counting up. Whether that’s true or not, I don’t know. But it seemed worthwhile to include two more variants in my testing:
Version 3:
for (var i = 99999, d; i >= 0; i--) {
d = document.createElement("div");
d.innerHTML = "DIV #" + i + "";
document.body.appendChild(d);
}
Version 4:
var j = 99999;
do {
var d = document.createElement("div");
d.innerHTML = "DIV #" + j + "";
document.body.appendChild(d);
} while (j--);
I tested each version 10 times. Each test ran in a fresh instance of Firefox v3.0.6 with no other open tabs. Here are the results:
There seems to be no significant difference here between different looping techniques. In light of this, I’d call it a matter of clarity/readability and somewhat personal preference. If you have to increment, obviously the for loop is clearer to read. For decrementing, either seems fine, though I like the do-while.
