Tuesday, January 11, 2011

Math.floor vs int vs uint cast

When you have a POSITIVE floating point number and want to round it down, it's better to use uint(2.33) than Math.floor(2.33). Casting positive number to uint directly is more than 17x (!!!) faster then Math.floor().
Check out the speed tests below:

private function testRoundDownPerformance():void
{
   var initialTime:int;
   var time:int;
   var i:int;
   const repCount:int = 100000000;
   
   initialTime = getTimer();
   for(i = 0; i < repCount; i++)
   {
      Math.floor(2.33);
   }
   time = getTimer() - initialTime;
   log("Math.floor: " + time + "ms");
   
   initialTime = getTimer();
   for(i = 0; i < repCount; i++)
   {
      int(2.33);
   }
   time = getTimer() - initialTime;
   log("int cast: " + time + "ms");
   
   initialTime = getTimer();
   for(i = 0; i < repCount; i++)
   {
      uint(2.33);
   }
   time = getTimer() - initialTime;
   log("uint cast: " + time + "ms");
}
Here are results:
Math.floor int cast uint cast
2.1 Ghz Intel Core 2 Duo, Windows 7
Flash Player 10.1
3620ms 218ms 203ms

In practice there's no such a big difference between int() and uint() cast, but uint function style cast is in fact a little faster.

0 komentarze:

Post a Comment

 
Powered by Blogger