UPDATED 07/01/08
I’ve been doing loads of optimising code recently and have come to the conclusion that on the whole, the Math class is evil (except for the Trig functions)
For many operations, it is better to use the int datatype. For example it is faster to do:
int(n) rather than Math.floor(n),
int(n)+1 instead of Math.ceil(n) and
if (n - int(n) < 0.5) n = int(n) else n = int(n)+1 rather than Math.round(n)
For other operations it is better to break it down into an if statement eg n = Math.abs(n) becomes:
if (n<0) n *=-1if (n<0) n = -n;
Also: if (x > n) x = n rather than x = Math.max(x, n) - the same obviously for Math.min
These aren't trivial savings either - by not using the Math class, you can get speed increases of up to 10 times!
However, the Math class is not the only culprit. Basically any time you access a class instance rather than putting in the function directly, you are losing speed. eg. using Math.sqrt((abx*abx)+(aby*aby)) is faster than using Point.distance(a, b). (Actually, often you don't need to use Math.sqrt - if you are checking 2 distances, then if you square the distance you are checking as well, you get the same result twice as fast!)
In fact, any time you create a variable it will have an impact on speed. You'd think that it be quicker to perform a sum once, store it in a variable and then retrieve it, but actually it is often quicker to do the sum more than once! The following functions illustrate what I mean:
var a:Point = new Point(20, 30);
var b:Point = new Point(40, 70);
function af():void
{
var d:Number = Math.sqrt(((a.x-b.x)*(a.x-b.x))+((a.y-b.y)*(a.y-b.y)));
}
function bf():void
{
var abx:Number = a.x-b.x;
var aby:Number = a.y-b.y;
var d:Number = Math.sqrt((abx*abx)+(aby*aby));
}
function cf():void
{
var d:Number = Point.distance(a, b);
}
The speed results for these functions over 1000000 iterations are:
test a:352
test b:393
test c:1458
So you can see that there are considerable savings in not using class methods and if you are only going to use a variable a couple of times, it may be faster not to create it at all.
There are a few exceptions to this - for example using 2 discrete variables is actually a little bit slower than accessing the x and y properties of a Point object - but not by much, so I err in favour of whichever is neater.
I also checked whether it was quicker to create a variable in a (class) function or to create a class property and use that. The difference in speed was minimal in favour of the class var, but I'm guessing the extra memory overhead would be the deciding factor in this case.
If I find any more I'll post them up here...
I've included the code I’ve used for my speed tests for you to download (updated 07/01/08).