Click here to Skip to main content
15,893,381 members
Articles / Programming Languages / Javascript
Tip/Trick

JavaScript: for(var i;i<len;++i) versus do{}while(--i)

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
18 Jul 2014CPOL1 min read 9.2K   1   1
You would have thought they'd have fixed this by now. I wanted to be sure, and here's the test.

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.

JavaScript
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++.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States
Just a crazy developer with crazy ideas of grandure.

What's that? Anal probe? NO, I said "Anal CODE!" Get that thing away, and get back to EditPlus.

Comments and Discussions

 
QuestionNot sure what the results should be Pin
Ivor O'Connor19-Jul-14 6:12
Ivor O'Connor19-Jul-14 6:12 
I ran the code as suggested, basically 480,480,300. Then changed it to alerts and it still came out basically the same. In firefox. Shouldn't the numbers be 300 across the board regardless of the type of loop?

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.