0

我有两个“Hello World”程序:

static void Main(string[] args) {
  Console.WriteLine("Hello World");
}

static void Main(string[] args) {
  string hw = "Hello World";
  Console.WriteLine(hw);
}

并且为这些中的每一个生成的 IL 代码是:

IL_0001:  ldstr       "Hello World"
IL_0006:  call        System.Console.WriteLine

IL_0001:  ldstr       "Hello World"
IL_0006:  stloc.0     // hw
IL_0007:  ldloc.0     // hw
IL_0008:  call        System.Console.WriteLine

我的问题是,为什么 C# 编译器默认不优化这个?

4

1 回答 1

1

C# 编译器针对Release构建进行了优化。Debug构建未优化!

优化[发布版本]

.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 1
    .locals init (
        [0] string hw)
    L_0000: ldstr "Hello World"
    L_0005: stloc.0 
    L_0006: ldloc.0 
    L_0007: call void [mscorlib]System.Console::WriteLine(string)
    L_000c: ret 
}

非优化[调试构建]

.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 1
    .locals init (
        [0] string hw)
    L_0000: nop 
    L_0001: ldstr "Hello World"
    L_0006: stloc.0 
    L_0007: ldloc.0 
    L_0008: call void [mscorlib]System.Console::WriteLine(string)
    L_000d: nop 
    L_000e: ret 
}
于 2013-02-16T05:15:39.633 回答