Different kinds of loop

JavaScript performance comparison

Revision 2 of this test case created by Jamie Mason

Info

In this revision I've updated the tests to call a function rather than count++; which is then not used.

I did this as in theory it's possible that some browsers will be able to see this variable is unused and optimise out that code so it's never run.

A real world app is unlikely to contain unused code, so this could skew the tests. - Jamie Mason / @GotNoSugarBaby

Preparation code

<script>
  var arr = [], obj = {};
 
  (function ()
  {
      for( var i = 0; i < 1000; i++ ) {
          arr[i] = 'value' + i;
          obj[i] = 'value' + i;
      }    
  }());
 
  function someFn (ix)
  {
      return ix * 5 + 1 / 3 * 8;
  }
 
</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
arr.forEach
if ('forEach' in arr)
{
    arr.forEach(function(value, i, arr) {
        someFn(i);
    });
}
else {
    // i'm not testing shims
    for( var i = 0; i < arr.length; i++ ) {
        someFn(i);
    }
}
pending…
var i in arr
for( var i in arr ) {
    someFn(i);
}
pending…
var i in arr (with hasOwnProperty check)
for( var i in arr ) {
    if( !arr.hasOwnProperty( i ) ) continue;
    someFn(i);
}
pending…
var i in obj
for( var i in obj ) {
    someFn(i);
}
pending…
var i in obj (with hasOwnProperty check)
for( var i in obj ) {
    if( !obj.hasOwnProperty( i ) ) continue;
    someFn(i);
}
pending…
for i < arr.length (without caching)
for( var i = 0; i < arr.length; i++ ) {
    someFn(i);
}
pending…
for i < arr.length (with caching)
for( var i = 0, max = arr.length; i < max; i++ ) {
    someFn(i);
}
pending…
for, counting down
for (var i = arr.length; i > 0; i--) {
    someFn(i);
}
pending…
while i < arr.length (without caching)
var i = 0;
do
{
    someFn(i);
    i++;
}
while (i < arr.length);
pending…
while i < arr.length (with caching)
var i = 0, max = arr.length;
do
{
    someFn(i);
    i++;
}
while (i < max);
pending…
while, counting down
var i = arr.length;
do
{
    someFn(i);
    i--;
}
while (i > 0);
pending…
while, counting down (2)
var i = arr.length - 1;
do
{
    someFn(i);
}
while (i--);
pending…
while, counting down (3)
var i = arr.length;
if (i > 0)
{
    do
    {
        someFn(i);
    }
    while (--i); // i must be greater than 0 here
}
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