Is there a more efficient way to calculate the absolute value of a subtraction expression

1.5k Views Asked by At

The question pretty much says it all. At the moment, I'm using Math.Abs(a - b) to calculate the absolute value of a subtraction expression, example 5 - 10 and 10 - 5 both returning 5.

Is there a more efficient way to do this, or it is the most efficient way?

1

There are 1 best solutions below

3
On

Please do not micro optimize your code until you know exactly where the problem is.

You can implement one your self and make it an inline function to reduce the cost of function call by using MethodImplAttribute.

If you are using Int32 Values and your inputs are not happen to be boundary values then you can use this

Abs(x) = (x ^ (x >> 31)) - (x >> 31)

but I suggest you to forget all about it, profile your application, you will see the real problem is somewhere else not in calling Math.Abs, You should always make your code readable first then tweak performance problems after you prove that they are really performance problems!

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.
(DonaldKnuth's paper "StructuredProgrammingWithGoToStatements")

read this please