2017-08-25 42 views
-5
using System.Collections.Generic; 
using System.IO 

哪個變種更快?什麼是更快,我該如何衡量這些東西?

This?

List<short> a = new List<short>(); 
a.Add(0); 
a.Add(1); 
a.Add(2); 
FileStream fs = new FileStream("file", FileMode.OpenOrCreate, FileAccess.Write){ 
    using (BinaryWriter bw = new BinaryWriter(fs)){ 
     foreach (short b in a){ 
     bw.Write(b); 
     } 
    } 
} 

or this?

string a = ""; 
a += "0"; 
a += "1"; 
a += "2"; 
File.WriteAllText("file", a); 

or this?

short[] a = new short[3]; 
a[0] = 0; 
a[1] = 1; 
a[2] = 2; 
FileStream fs = new FileStream("file", FileMode.OpenOrCreate, FileAccess.Write){ 
using (BinaryWriter bw = new BinaryWriter(fs)){ 
    foreach (short b in a){ 
     bw.Write(b); 
    } 
} 

}

我想知道如何快速的每個小部分代碼的編譯,以及我如何可以測量速度自己。

+6

[哪個更快?](https://ericlippert.com/2012/12/17/performance-rant/) –

+2

如果您對執行時間感興趣,可以使用[StopWatch](http:// msdn。 microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx)你可以測量。 – Amogh

+2

類似HashSet的類被記錄爲在O(1)時間內執行。這在msdn上有記錄。但是像你提到的常規方法沒有這樣的時間規格。你需要自己進行基準測試。只需在所有情況下創建相同的場景。運行過程例如10000次。確保在開始時啓動計時器並在10000次重複後打印出時間。然後比較兩種情景之間的時間並重復2到4次以擺脫可能的臨時性能問題。 –

回答

0

除非你知道發生了什麼,否則不要試圖猜測性能。相反,重複您的操作足夠的時間,需要幾秒鐘才能進行,並使用秒錶測量每個版本。嘗試單獨進行基準測試(並非所有測試都在同一基準測試中),因爲如果編譯器檢測到可以使用之前的測試結果進行下一次測試,編譯器可能會改變您的結果。

相關問題