More testing on Actionscript’s Math class

As you may have noticed I’m somewhat critical regarding the AS3 Math class. I’m a bit sick to be honest and work was flowing as I wanted to so I took 30 minutes off to test some stuff.

Flooring a number

Getting the nearest low integer of a number is usually achieved with Math.floor(number). If we didn’t have it, we would probably typecast the number to an integer and get the same result. So I looped both methods one million times and measured the results.

Math.floor(number) performed around 150 milliseconds
int(number) performed around 5 miliseconds

Now the bad news is that this works for positive numbers, using int(number) for negative signed numbers doesn’t produce a floored integer. For example int(-2.4) returns -2 where it should return -3.

Rounding a number

Rounding a number will return the closest integer of that number. Again this is usually achieved with Math.round(number) but we can also do this:

One million iterations after the results are as follow:

Math.round(number) took around 165 milliseconds
int(number + 0.5) took around 5 miliseconds

Same issue applies regarding negative signed numbers though, so keep that in mind, but the question is…

Are you feeling the urge of writing a new Math class?

This way we could deal with both performance and doing some arrangements to make negatives work correctly. Problem with this is that we will be calling a static method from an external class. A full working rounding method called one million times took 180 milliseconds against the 165 milliseconds from Math.round(number) method, so there’s loss instead of gain.

Bottom line is that this kind of stuff is a bit like using multiplications over divisions. Depends on a lot of stuff. If your display objects move on a positive x and y axis, you can do it like there’s not tomorrow, just typecast to integer whatever you need to round, but all in all, unless you have millions of Math class operations to do, you won’t even notice the difference.

See you soon,
Vlad

Posted: August 9th, 2009
at 12:00am by Vlad

Tagged with , ,


Categories: The code of VGS

Comments: No comments