且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C#编译器的优化程度如何?

更新时间:2023-11-10 20:53:10

以下是您的代码段的x64反汇编:

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

这意味着,JIT执行了死代码消除(ret = return Main函数只是立即退出).

编译器仅执行一些基本优化,但大部分工作留给了JIT,以针对其运行的平台进行优化.

尽管我同意编译器在这种情况下当然可以执行此优化,因为它与平台无关.

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()...

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.