JavaScript Loops

JavaScript performance comparison

Revision 3 of this test case created

Info

See this discussion in a Codecademy group forum.

I've taken the test code from this comment and modified it only slightly. In particular, I changed <= to < everywhere, because <= involves two comparisons (less than OR equal), which is unnecessary. I also changed the number of repetitions to 10 thousand because JSPerf times each test hundreds of times anyway.

Scroll down to run the tests and a little further down to see charts of previous results for different browsers.

[2013-01-25] update: fixed the bug that caused wrong results. Set the iteration count to 100 thousand.

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var i = 0, j = 0, k = 0, max = 100000; // loop variables
   
    var while_loop = function() {
        i = 0;
        while (i < max) {
          i++;
        }
    }
   
    var while_minus = function() {
        while (max--) {
        }
    }
       
    // the loop body is intentionally empty
    var for_loop = function() {
        for (k = 0; k < max; k++) {  }
    }
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
While
while_loop();
pending…
While and break
while_minus();
pending…
For
for_loop();
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment