algorithmperformancetheoryabsolute-value

Which is the fastest way to get the absolute value of a number


Which is the fastest way to implement an operation that returns the absolute value of a number?

x=root(x²)

or

if !isPositive(x):
    x=x*(-1)

Actually this question can be translated as, how fast is an if (and why please).

My college programing professors always told me to avoid ifs for they are extremely slow, but I always forgot to ask how slow and why. Does anybody here know?


Solution

  • Conditionals are slower than plain arithmetic operations, but much, much faster than something as silly as calculating the square root.

    Rules of thumb from my assembly days: