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

后端 未结 14 889
陌清茗
陌清茗 2020-12-07 19:10

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

x=root(x²)

or

if !isPositiv         


        
14条回答
  •  孤城傲影
    2020-12-07 19:18

    The time taken to do a square root is much greater than the time taken to do an conditional. If you have been taught to avoid conditionals because they are slow, then you have been misinformed. They are a good deal slower than trivial operations like adding or subtracting integers or bit shifting - which is why unrolling loops can be of benefit only if you are doing such trivial operations. But in the grand scheme of things conditionals are good and fast, not bad and slow. To do something as complicated as call a function or calculate a square root to avoid a conditional statement is crazy.

    Also, instead of (x = x * -1) why not do (x = 0 - x)? Maybe the compiler will optimize them the same, but isn't the second one simpler anyway?

提交回复
热议问题