Which is the fastest way to implement an operation that returns the absolute value of a number?
x=root(x²)
or
if !isPositiv
I'm doing some retro graphics programming in C for 8088/8086 and calling abs()
is time consuming so I've replaced it with:
/* assuming 'i' is int; this WILL NOT WORK on floating point */
if (i < 0) {
i = ~i + 1;
}
The reason this is faster is because it essentially trades a CALL
in assembly for a JNE
. Calling a method changes a couple of registers, pushes several more, pushes arguments onto the stack, and can flush the prefetch queue. Plus these actions need to be reversed at the end of the function and all of this is very expensive to the CPU.