C#编译器的优化程度如何? [英] How optimized is the C# compiler?
问题描述
这段代码的IL代码(由 https://dotnetfiddle.net 生成):
public class Program
{
public static void Main()
{
int i = 10;
if (i < 4)
Console.WriteLine("Hello World");
}
}
包含ldstr"Hello World".
编译器是否不知道Console.WriteLine永远不会执行?
此代码的IL代码:
public class Program
{
public static void Main()
{
if (10 < 4)
Console.WriteLine("Hello World");
}
}
不包含ldstr命令.
现在我很困惑..NET编译器真的那么愚蠢吗? 两个示例的C#/IL代码完全相同:什么也不做.但是第一个示例的IL代码比另一个大.好的编译器不应该只是调用构造函数而不执行任何操作.
是的,我已经阅读了 this ,但是我不是在谈论其他生成的本地人.
如果i
是属性或公共变量,则可以从另一个线程对其进行修改.但是i
仅存在于Main()中...
以下是您的代码段的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.
这篇关于C#编译器的优化程度如何?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!