第一個會更有效率。編譯器將其轉換爲以下單呼:
StringBuilder sb = new StringBuilder();
sb.Append("HelloHowareyou");
測量性能
知道這是更快的來衡量它的最好辦法。我會得到開門見山:這裏的結果(較小的時間意味着更快):
sb.Append("Hello" + "How" + "are" + "you") : 11.428s
sb.Append("Hello").Append("How").Append("are").Append("you"): 15.314s
sb.Append(a + b + c + d) : 21.970s
sb.Append(a).Append(b).Append(c).Append(d) : 15.529s
給出的數字是執行操作100萬次在緊密循環的秒數。
結論
- 最快的是使用字符串和
+
。
- 但是,如果你有變量,使用
Append
比+
快。由於對String.Concat
的額外呼叫,第一個版本較慢。
如果你想測試這個自己,這是我用來獲取上述定時程序:
using System;
using System.Text;
public class Program
{
public static void Main()
{
DateTime start, end;
int numberOfIterations = 100000000;
start = DateTime.UtcNow;
for (int i = 0; i < numberOfIterations; ++i)
{
StringBuilder sb = new StringBuilder();
sb.Append("Hello" + "How" + "are" + "you");
}
end = DateTime.UtcNow;
DisplayResult("sb.Append(\"Hello\" + \"How\" + \"are\" + \"you\")", start, end);
start = DateTime.UtcNow;
for (int i = 0; i < numberOfIterations; ++i)
{
StringBuilder sb = new StringBuilder();
sb.Append("Hello").Append("How").Append("are").Append("you");
}
end = DateTime.UtcNow;
DisplayResult("sb.Append(\"Hello\").Append(\"How\").Append(\"are\").Append(\"you\")", start, end);
string a = "Hello";
string b = "How";
string c = "are";
string d = "you";
start = DateTime.UtcNow;
for (int i = 0; i < numberOfIterations; ++i)
{
StringBuilder sb = new StringBuilder();
sb.Append(a + b + c + d);
}
end = DateTime.UtcNow;
DisplayResult("sb.Append(a + b + c + d)", start, end);
start = DateTime.UtcNow;
for (int i = 0; i < numberOfIterations; ++i)
{
StringBuilder sb = new StringBuilder();
sb.Append(a).Append(b).Append(c).Append(d);
}
end = DateTime.UtcNow;
DisplayResult("sb.Append(a).Append(b).Append(c).Append(d)", start, end);
Console.ReadLine();
}
private static void DisplayResult(string name, DateTime start, DateTime end)
{
Console.WriteLine("{0,-60}: {1,6:0.000}s", name, (end - start).TotalSeconds);
}
}
請參閱http://stackoverflow.com/questions/9132338/how-many-string-objects-will-be-created-when-using-a-plus-sign/9132374#9132374。這已被覆蓋*致死* :-) – 2012-08-13 16:04:43
你可以找到[這個分析](http://www.dotnetperls.com/stringbuilder-performance)有趣 – Steve 2012-08-13 16:08:11
我的問題是 - 你爲什麼要做「你好」+ 「如何」等,當「HelloHow」會好嗎?這個問題的實際問題是什麼,因爲我的答案因技術原因而受到打擊,我認爲這不是重點...... – Charleh 2012-08-13 16:24:23