Search code examples
c#micro-optimizationshort-circuiting

Can the compiler/JIT optimize away short-circuit evaluation if there are no side-effects?


I have a test which goes:

if(variable==SOME_CONSTANT || variable==OTHER_CONSTANT)

In this circumstances, on a platform where branching over the second test would take more cycles than simply doing it, would the optimizer be allowed to treat the || as a simple |?


Solution

  • In this circumstances, on a platform where branching over the second test would take more cycles than simply doing it, would the optimizer be allowed to treat the || as a simple |?

    Yes, that is permitted, and in fact the C# compiler will perform this optimization in some cases on && and ||, reducing them to & and |. As you note, there must be no side effects of evaluating the right side.

    Consult the compiler source code for the exact details of when the optimization is generated.

    The compiler will also perform that optimization when the logical operation involves lifted-to-nullable operands. Consider for example

    int? z = x + y;
    

    where x and y are also nullable ints; this will be generated as

    int? z;
    int? temp1 = x;
    int? temp2 = y;
    z = temp1.HasValue & temp2.HasValue ? 
      new int?(temp1.GetValueOrDefault() + temp2.GetValueOrDefault()) :
      new int?();
    

    Note that it's & and not &&. I knew that it is so fast to call HasValue that it would not be worth the extra branching logic to avoid it.

    If you're interested in how I wrote the nullable arithmetic optimizer, I've written a detailed explanation of it here: https://ericlippert.com/2012/12/20/nullable-micro-optimizations-part-one/