Faster Math.abs()

ActionScript, Code snippets

Quick post 🙂 This function returns the absolute value of a specified number. This is +/- 24x faster than the regular Math.abs().

function abs( value ) {
return value < 0 ? -value : value;
}

If you are using Haxe, then mark the function as inline, to be even faster. If you’re not using Haxe but have performance heavy code, you could manually inline it, to avoid the function call.


inline function abs<T:Float>(value:T):T {
return value < 0 ? -value : value;
}

7 responses to “Faster Math.abs()”

  1. Even faster:

    return (value ^ (value >> 31)) – (value >> 31);

  2. Hey, nice reflection!
    How can you measure these kind of operations time?

  3. And if you want it even faster you don’t use it as a function but inline the code.

  4. Mark Knol says:

    @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.

  5. Solenoid says:

    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.

  6. Mark Knol says:

    @Solenoid Cool you made a javascript performance test, nice to see this applies to actionscript ánd javascript.

  7. Robert says:

    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.

Say something interesting

Please link to code from an external resource, like gist.github.com.