HullBreach

JavaScript Optimization Tests

The following time tests are all performed by running 1,000,000 iterations and reporting results in milliseconds, averaged after 5 times. Some results are obvious, while others are surprising. These tests can be used as guidelines for optimizing code.

Absolute Value (Integer)

  1. y = Math.abs(x);
  2. y = (x^(x>>31))-(x>>31);
  3. y = x<0?-x:x;
FF2.0IE7.0Op9.25
1153819281443
2147510721456
311319561106

Truncation

  1. y = Math.floor(x); (Note: This will round down negative values.)
  2. y = x|0;
  3. y = x>>0;
FF2.0IE7.0Op9.25
1154420001543
21212875922
31191850922

For Loops

  1. for(var iter=1; iter<times; iter++){ }
  2. for(var iter=times-1; iter>0; iter--){ }
  3. for(var iter=times; --iter>=0;){ }
FF2.0IE7.0Op9.25
1857631784
2547369459
3384222334

Function Calls

  1. x = function(){ ... }
  2. x = setx(); function setx(){ ... }
FF2.0IE7.0Op9.25
175024031522
286526531141

Swapping Values

  1. var hold=x; x=y; y=hold;
  2. x^=y; y^=x; x^=y;
FF2.0IE7.0Op9.25
1154612061309
2207912901900