![](/img/trans.png)
[英]How to rewrite a piece of code without using string.Join and StringBuilder
[英]Stringbuilder in foreach slower than in for and String.Join() SUCKS on collections?
在 SO 上看到一個關於加入字符串的問題后,我已經做了一些測試,並了解到在 foreach 中加入字符串比使用 for 循環和使用數組中的索引要慢。 由於對數組的邊界檢查,for循環不應該變慢嗎? (對 foreach 上不存在的字符串 [i] 進行綁定檢查)。
我不明白的另一件事是列表上的 string.Join() 緩慢...
編輯:將錯誤更新並將源更新為最終源(刪除最后一個“,”)
這是測試的結果:
DEBUG: AMD PHENOM II X4 3GHZ StringBuilder foreach System.Action Time: 4077ms (12025926) StringBuilder for System.Action Time: 4032ms (11895082) String.Join System.Action Time: 5338ms (15744918) INTEL XEON W3503 @ 2.4GHZ / 12GB DDR3 StringBuilder foreach System.Action Time: 4661ms (10926950) StringBuilder for System.Action Time: 4202ms (9849590) String.Join System.Action Time: 6466ms (15156149) RELEASE: AMD PHENOM II X4 3GHZ StringBuilder foreach System.Action Time: 3897ms (11496978) StringBuilder for System.Action Time: 3719ms (10970899) String.Join System.Action Time: 5307ms (15655162) INTEL XEON W3503 @ 2.4GHZ / 12GB DDR3 StringBuilder foreach System.Action Time: 4533ms (10625128) StringBuilder for System.Action Time: 4168ms (9770765) String.Join System.Action Time: 7173ms (16813036) (why in the world xeon slower than in debug with string.join?) FOR A GOOD LAUGH LOOK AT THE END.
這是來源:
public static void Main(string[] Args)
{
List<string> strings = new List<string>() {};
for (double d = 0; d < 12000; d++) {
strings.Add(d.ToString());
}
GC.Collect();
GC.WaitForPendingFinalizers();
Performance(() =>
{
StringBuilder sb = new StringBuilder();
foreach (string s in strings)
{
sb.Append(s);
sb.Append(",");
}
sb.Remove(sb.Length - 1, 1);
}, "StringBuilder foreach");
GC.Collect();
GC.WaitForPendingFinalizers();
Performance(() =>
{
StringBuilder sb = new StringBuilder();
int max = strings.Count-1;
int i;
for (i = 0; i < max; i++)
{
sb.Append(strings[i]);
sb.Append(",");
}
sb.Append(strings[i]);
}, "StringBuilder for");
GC.Collect();
GC.WaitForPendingFinalizers();
Performance(() =>
{
string s = string.Join(",", strings);
}, "String.Join");
}
public static void Performance(Action fn, string prefix)
{
var timer = new Stopwatch();
timer.Start();
for (var i = 0; i < 10000; ++i)
{
fn();
}
timer.Stop();
Console.WriteLine("{0} {1} Time: {2}ms ({3})", prefix, fn.ToString(), timer.ElapsedMilliseconds, timer.ElapsedTicks);
}
字符串是否像 foreach 中的值類型一樣被復制? 由於速度幾乎相同...
編輯:
澄清為什么int max = strings.Count-1;
可能是與人們所說的相反的優化(並且測試證明了這一點):
我們沒有在 arrays 上工作,並且集合來自外部 scope 到迭代它的方法。 如果它是for循環中的strings.Length,那可能會改變(就像另一個線程改變集合一樣)..但這不是原因,原因是我們正在讀取一個變量而不是調用一個方法(屬性獲取)和它僅提供 5% 的性能。 這不是邊界檢查的編譯時優化,因為沒有人可以提前知道“最大值”值。 這取決於每次調用該方法時字符串的內容是什么。
編輯2:
使用更大的字符串但數量相同的版本進行了測試,請對 String.Join() 笑一笑:
List<string> strings = new List<string>() {};
for (double d = 0; d < 12000; d++) {
strings.Add("ikugluglizuglkuhiugpiugiugholiugholiughpiuhziuhzuiugloiu" + d.ToString());
}
// AMD PHENOM:
// StringBuilder foreach System.Action Time: 10080ms (29732687)
// StringBuilder for System.Action Time: 9659ms (28490593)
// String.Join System.Action Time: 24509ms (72292291)
// INTEL XEON:
// StringBuilder foreach System.Action Time: 9790ms (22947294)
// StringBuilder for System.Action Time: 9140ms (21425490)
// String.Join System.Action Time: 21114ms (49490839)
這可能對 arrays 有好處,但在 collections String.Join 很糟糕,對於大字符串更是如此!
如果您想比較,僅供參考:
Windows 7 64bit
CPU Type QuadCore AMD Phenom II X4 945
CPU Clock 3000 MHz
L3 Cache 6 MB (On-Die, ECC, NB-Speed)
North Bridge Clock 2010.8 MHz
Memory 8190 MB
Memory Bus 804.3 MHz DDR3-1600
Motherboard Chipset AMD 790X, AMD K10
Memory Timings 8-9-9-24 (CL-RCD-RP-RAS)
Command Rate (CR) 1T
由於對數組的邊界檢查,for循環不應該變慢嗎?
不,CLR 可以將其優化為 1 檢查它是否可以驗證邊界。 這使得
int max = strings.Count - 1;
一個糟糕的優化。 在 FX 1.1 中它會花費你。 (這也是不正確的)。
foreach
必須做更多的工作(通過 Eumerator)。 請注意差異很小。
查看 ILSpy 中的 IL 代碼。
foreach 循環有一個隱式的 try.. finally 循環沒有。
在 foreach 內部也有對 MoveNext 的隱式調用。 MoveNext 有很多開銷,包括在最終對列表執行索引操作以獲取條目之前進行版本更改檢查。
理論上 foreach 可以更快,但它顯然比裸 for 循環做得更多。
這是vs2010下的。 不確定其他版本如何處理這個問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.