Search code examples
c#optimization

Compiler Magic: Why?


I just noticed that given the following code:

if (x.ID > 0 && !x.IsCool)

the Microsoft C# 3.0 (VS2008 SP1) compiler will optimize it to this:

if (!((x.Id <= 0) || x. IsCool))

This is on Debug build without Optimization enabled. Why does the compiler do that? Is it faster in terms of execution?

I used Reflector to find that out (I was actually looking for something different)


Solution

  • The C# compiler certainly does not generate an equivalent C# code for your snippet. It's compiled down to IL. Basically, what you are seeing (from Reflector, I guess) is the equivalent C# code that a decompiler spits out for that IL.

    1. The language specification does not say what an "unoptimized" code is. The C# compiler is allowed to generate any valid, functionally equivalent code. Even without optimization switch on, the compiler might do basic optimizations. Beside that, you can't say what is natural for the compiler and whether the compiler deliberately optimized it or not.

    2. The if statement as a whole is evaluated as a sequence of conditional branches based on the values of each individual expression specified in the "and" clause. The expression is not evaluated in a single code block with "and" instructions. The output of the decompiler is something inferred from those branches. The decompiler cannot always infer the original expression you wrote. It just outputs something equivalent.

    Similarly, the difference between this snippet:

    if (a) { something(); }
    else { somethingElse(); }
    

    and this snippet:

    if (!a) { somethingElse(); }
    else { something(); }
    

    is not something you'd distinguish by seeing the compiled code.