blog

Faster floor, round, ceil for ActionScript

It is always nice to add some speed boost to your performance critical algorithms. Making some native Math function’s alternatives perform up to 8 times faster is possible. Lets have a look at the basic ones Math.floor(), Math.round(), Math.ceil():

faster alternative for Math.floor()

var ni:int = n;
return (n < 0 && n != ni) ? ni - 1 : ni;

faster alternative for Math.round()

return n < 0 ? n + .5 == (n | 0) ? n : n - .5 : n + .5;

faster alternative for Math.ceil()

var ni:int = n;
return (n >= 0 && n != ni) ? ni + 1 : ni;

Here is an app runnig some unit tests and speed tests. I have wrapped both custom methods and Math methods into functions and count out empty method call time to correct the results.

Faster ceil, round, floor – wonderfl build flash online

The results talks for itself:

Math.floor(): 844 ms
floor(): 125 ms
Math.round(): 859 ms
round(): 109 ms
Math.ceil(): 766 ms
ceil(): 93 ms

Where to go from here:

Inline Math.ceil() Part II