Faster Math.abs() (7)
January 28th, 2009, under actionscript, Code snippets.
Quick post
This function returns the absolute value of a specified number. This is +/- 24x faster than the regular Math.abs().
public function abs( value:Number ):Number
{
return value < 0 ? -value : value;
}
{
return value < 0 ? -value : value;
}



















Even faster:
return (value ^ (value >> 31)) – (value >> 31);
Hey, nice reflection!
How can you measure these kind of operations time?
And if you want it even faster you don’t use it as a function but inline the code.
@Steven: Thanks, it is slightly faster. It’s hard too learn bitwise shifting, I need too learn more about it. But when you know it, it’s very usefull. I use it alot for calculation with colours.
@André: It is very simple. Create a variable and get the current time (timer1) with getTimer(). Then run a loop (with the test – function) about 15000 times. After running the loop, get the current time again (timer2). Then I trace timer2 – timer1. I use this setup for the another testfunction too, and compare the results. Too be sure it is really faster, run the test multiple times.
@Mario: Wow, I knew static functions are slower, but I didn’t know it does matter to type inline or having a separate function in the same scope.
Did a test for you: http://jsperf.com/absolute-value-speed/
Steven Sacks’s bitwise method wins hands down.
PS: copy-paste from this website contains white space characters… annoying inside code.
@Solenoid Cool you made a javascript performance test, nice to see this applies to actionscript ánd javascript.
It should be noted that Steven’s method ONLY WORKS FOR INTEGERS! It’s dangerous to use that method on :Number as those include floating point which are stored as sign, exponent, significand. It also assumes a 32-bit execution, which for the time being Flash will be, but some day they will have to accept the future is 64-bits wide.