views:

105

answers:

3

Which of these would be faster for a static method called billions of times per nanosecond:

Method 1:

static bool DualConditional(int value)
{
   return A(value) && B(value);
}

Method 2:

static bool DualConditional(int value)
{
   if(!A(value)
      return false;

    if(!B(value)
      return false;
}
+7  A: 

They should both be the same.

The first will short circuit and return if A() is false.

The first is also much easier to read and understand. Even if performance was marginally worse, I'd use this code. Premature micro-optimization is worthless when readability is sacrificed.

Justin Niessner
Thank you for the clarification! This is post-mature, desperate optimization :D
bufferz
+2  A: 

&& short circuits, which means the right side is only evaluated if the left side passes, in this case. So yes,

return A(value) && B(value);

is the rough quivalent of

if (A(value))
  if (B(value))
     return true;

return false;
Anthony Pegram
+2  A: 

Will the C# compiler turn Method1 into Method2 automatically

No

and skip B() if A() is false?

Yes

In general, the code like

return A(value) && B(value);

Is faster than

if(!A(value)
  return false;

if(!B(value)
  return false;

Because the first variant can be converted to x86 code that doesn't use jumps.

For instance in code:

    private static bool B_1(int value)
    {
        return value < 5;
    }

    private static bool B_2(int value)
    {
        if (value < 5)
            return true;
        else
            return false;
    }

For B_1 C# generated a slightly faster x86 code than for B_2.

In this particular situation I would say that it depends on A() and B(). I would run it under profiler to see which is faster.

Max
Thanks for adding detail in addition to what others wrote above. Any insight for 64-bit runtime?
bufferz
Same is true for x64. I just checked. The first B_1 version saves one conditional jump. So it is a bit faster.
Max