JavaScript Loop Optimization

After reading an article about optimizing loops in JavaScript, I put together this page to test the ideas presented. Basically, this just increments a counter one million times and displays the elapsed time. Pretty simple.

Update: I found another article that describes a JavaScript implementation of Duff's Device, an even more efficient way of doing loops. It works!

Update (Feb 8, 2006): I've applied the do/while technique below to a new test of JavaScript optimization for a custom in_array() method (emulating the PHP function of the same name).

Slower Faster Duff's

Start time:

End time:

Elapsed time:

Result:

Start time:

End time:

Elapsed time:

Result:

Start time:

End time:

Elapsed time:

Result:


Number of iterations:


function doSlow()
{
   /* common code */

   for (l=1;l<iterations+1;l++)
   {
      testVal++;
   }

   /* common code */
}
	
function doFast()
{
   /* common code */

   l = iterations;
   do
   {
      testVal++;
   } while (--l);

   /* common code */
}
	
function doDuffs()
{
   /* common code */

   n = iterations % 8;
   while (n--)
   {
      testVal++;
   }

   n = parseInt(iterations/8);
   while (n--)
   {
      testVal++;
      testVal++;
      testVal++;
      testVal++;
      testVal++;
      testVal++;
      testVal++;
      testVal++;
   }

   /* common code */
}
	

 

Was this page useful to you? Loading...