0

2つの「HelloWorld」プログラムがあります。

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

ReleaseC#コンパイラはビルド用に最適化します。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 に答える