2010-01-18 33 views

回答

14

底線是,寫入控制檯必然會主宰這裏的性能 - 即使你將它重定向到某種「空」接收器。

的區別,國際海事組織,是

Console.WriteLine(i); 

是簡單的讀...所以這就是我會使用,直到我倒是證明,使用稍微少可讀的形式給予了具體的好處。在這種情況下,任何形式都不會以i爲整數,因爲有WriteLine(int)的超載。甲略微更有趣的問題是這兩條線之間:

Console.WriteLine("Some format {0} stuff", i); 
Console.WriteLine("Some format {0} stuff", i.ToString()); 

第一種形式將框的整數;第二個不會。性能的差異? Nothing significant.

+0

我還想補充一點,你不可能在嚴格的性能限制循環內寫入控制檯 - 這通常是性能差異顯現的唯一地方。 – redcalx

2

沒有實際的區別,都會調用ToString將數字轉換爲字符串。

1

There 應該沒有區別。如果你自己沒有明確這樣做,Console.WriteLine方法應該自動調用ToString()方法。然而,如果你看看IL代碼,我很驚訝地發現它們並不相同。顯然,Console.WriteLine命令(INT)必須​​在內部整型轉換爲十進制字符的字符串,但這不是從IL明顯...

對於此代碼:

static void Main(string[] args) 
{ 
    int i = 34; 
    Console.WriteLine(i); 
    Console.WriteLine(i.ToString()); 

} 

的IL是

.method private hidebysig static void Main(string[] args) cil managed 
{ 
    .entrypoint 
    .maxstack 1 
    .locals init (
     [0] int32 i) 
    L_0000: nop 
    L_0001: ldc.i4.s 0x22 
    L_0003: stloc.0 
    L_0004: ldloc.0 
    L_0005: call void [mscorlib]System.Console::WriteLine(int32) 
    L_000a: nop 
    L_000b: ldloca.s i 
    L_000d: call instance string [mscorlib]System.Int32::ToString() 
    L_0012: call void [mscorlib]System.Console::WriteLine(string) 
    L_0017: nop 
    L_0018: ret 
} 

使用Jon的例子,(帶的String.Format),第一種情況(W/O的ToString())的值盒裝... 代碼:

int i = 34; 
    Console.WriteLine(string.Format("Some format {0} stuff", i)); 
    Console.WriteLine(string.Format("Some format {0} stuff", i.ToString())); 

的IL是

.method private hidebysig static void Main(string[] args) cil managed 
{ 
    .entrypoint 
    .maxstack 2 
    .locals init (
     [0] int32 i) 
    L_0000: nop 
    L_0001: ldc.i4.s 0x22 
    L_0003: stloc.0 
    L_0004: ldstr "Some format {0} stuff" 
    L_0009: ldloc.0 
    L_000a: box int32 
    L_000f: call string [mscorlib]System.String::Format(string, object) 
    L_0014: call void [mscorlib]System.Console::WriteLine(string) 
    L_0019: nop 
    L_001a: ldstr "Some format {0} stuff" 
    L_001f: ldloca.s i 
    L_0021: call instance string [mscorlib]System.Int32::ToString() 
    L_0026: call string [mscorlib]System.String::Format(string, object) 
    L_002b: call void [mscorlib]System.Console::WriteLine(string) 
    L_0030: nop 
    L_0031: ret 
} 
+0

如果'i'是一個值類型的實例,但不是.Net原語,則在這種情況下有所不同。在這種情況下,它會將該值裝箱以調用WriteLine(對象)覆蓋。直接在值類型上調用ToString()不應該導致框IIRC – JaredPar

+0

@JaredPar - 只要值類型重寫Object.ToString,就不會發生裝箱。 –

+0

我做了測試,並編輯了我的答案...看看IL ...沒有發生拳擊,並且,令人驚訝的是,沒有明確地調用ToString()發生.. –

0

首先,優化到這個水平真的不會讓你任何好處。優化你的算法,然後配置文件,並優化你的瓶頸。我將重點放在哪個更易於閱讀和維護(在這兩種情況下,我更喜歡第一個...)

但是,從性能角度來看,第一個通常會更好。如果你用int來調用第一個,它就會有效地調用第二個。用字符串,你會得到一個額外的(無操作)方法調用。

相關問題