2013-02-16 63 views
0

我有兩個 「Hello World」 的程序:C#編譯器是否默認優化程序?

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#編譯器默認默認

+0

你對優化標誌? – 2013-02-16 04:47:27

+0

@KevinHikaruEvans nope,實際上在LinqPad上運行它,我希望如果C#編譯器默認會做一些事情! – 2013-02-16 04:48:16

+1

第二個IL通常用於調試輸出。另外,如果程序沒有被調試,JIT可能會消除這種情況。 – leppie 2013-02-16 04:49:38

回答

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 
}