2009-12-08 44 views
3

從性能的角度來看,使用「Example1」更好嗎?我假設「例2」將在每個迭代堆上創建一個新的字符串,而「例1」不會.......NET字符串性能問題

例1:

StringBuilder letsCount = new StringBuilder("Let's count! "); 
string sep = ", "; 
for(int i=; i< 100; i++) 
{ 
    letsCount.Append(i + sep); 
} 

例2:

StringBuilder letsCount = new StringBuilder("Let's count! "); 
for(int i=; i< 100; i++) 
{ 
    letsCount.Append(i + ", "); 
} 
+0

+1暴露我的StringBuilder的使用我以前從來沒見過......內部非自動轉換字符串參數轉換爲字符串(如果這是描述它的正確方法)...(並且不會在MSDN中記錄)。 – BillW 2009-12-08 07:24:17

回答

12

.NET CLR比這更聰明。它「interns」字符串文字,因此只有一個實例。

還值得注意的是,如果你真的關心字符串連接,你會希望將單一的Append調用變成兩個append調用。但實際情況是,兩次通話的開銷可能超過任何小的連接成本。無論哪種情況,除非在非常受控的條件下,這可能幾乎不可測量。

+0

我認爲你應該嘗試一下,使用秒錶,它是非常好的衡量標準,使用一個stringbuilder的速度已經超過了4-5個連接。 – 2009-12-08 05:55:50

+0

我很清楚使用stringbuilder進行多個連接的好處。我指的是Append(i + sep)和Append(i)之間的區別;追加(SEP); ×100 – Josh 2009-12-08 06:15:01

+0

我確實接受了你的建議,但時間到了。 x100 - 0ms(72 ticks)vs 0ms(61 ticks),x100000 - 32ms(71,517 ticks)vs 26ms(58,870 ticks) – Josh 2009-12-08 06:26:15

2

它們是相同的。

1

其實更快的方式做這將是

string letsCount = "Let's count! "; 
string[] numbers = new string[100]; 
for(int i=0; i< 100; i++) 
{ 
    numbers[i]=i+", "; 
} 
String.Join(letsCount, numbers); 

See here

+0

非常有趣,謝謝你的鏈接。我將來必須記住這一點。在有100個連接字符串之後,我會好奇地看到那個圖表...... – 2009-12-10 02:39:03