Search code examples
c#.netoptimizationcompiler-optimizationcil

How optimized is the C# compiler?


The IL code (generated with https://dotnetfiddle.net) of this piece of code:

public class Program
{
    public static void Main()
    {
        int i = 10;
        if (i < 4)
            Console.WriteLine("Hello World");
    }
}

contains ldstr "Hello World".

Shouldn't the compiler know that Console.WriteLine never gets executed?

The IL code of this:

public class Program
{
    public static void Main()
    {
        if (10 < 4)
            Console.WriteLine("Hello World");
    }
}

doesn't contain the ldstr command.

Now i'm confused.. is the .NET compiler really that stupid? The C#/IL code of both examples do exactly the same: nothing. But the IL code of the first example is larger than the other. Shouldn't a good compiler just call the constructor and do nothing..?

Edit:

Yes i already read this but i'm not talking about additional generated locals.

If i would be a propertie or a public variable, it would possible to modify it from another thread. But i only exists in Main()...


Solution

  • Here's the x64 disassembly of your snippet:

    00007FF7C6083E0E  add         byte ptr [rax],al  
    --- C:\Dev\Temp\Test\ConsoleApp\ConsoleApp\Program.cs --------------------------
                int i = 10;
    00007FF7C6083E10  ret  
    --- No source file -------------------------------------------------------------
    

    Which means, the JIT performed dead code elimination (ret = return, the Main function simply exits immediately).

    The compiler only performs some basic optimizations, but the bulk of it is left to the JIT, to optimize for the platform it runs on.

    Though I agree the compiler certainly could perform this optimization in this case, as it's platform-independent.