将 string.Format 与许多参数一起使用时,哪个性能更高:字符串或 StringBuilder?

What is more performant when using string.Format with many args: string or StringBuilder?

是否像这样使用 string.Format

string.Format(txt, arg0, arg1, arg2, arg3, arg4,...)

与说 txt+=args; 相同,因此它每次从 args 列表中附加一个新字符串时都会创建一个新对象?更好地使用 StringBuilder.Format ?

如果您只使用字符串格式,请使用 string.Format。 如果你使用很多字符串连接 and/or 字符串形式,使用 StringBuilder.

看看这个: https://support.microsoft.com/en-us/kb/306822

我上面的评论意味着你应该在你的环境中测试你的表现。使用 Stopwatch 实例,创建一个在 string.Format 和 StringBuilder.AppendFormat 上运行至少十万次的循环,然后测量 Stopwatch.ElapsedMilliseconds 中的值。这将使您大致了解差异。

在我的环境中,这两种方法非常相同。 100000 次循环的区别是 StringBuilder 有 2/3 毫秒的优势,但士气是:

不要进行微优化

(除非你完全清楚结果值得付出努力)。

样本:

string s1 = "Argument 1";
string s2 = "Argument 2";
string s3 = "Argument 3";
string s4 = "Argument 4";
string s5 = "Argument 5";
string s6 = "Argument 6";
string s7 = "Argument 7";
string s8 = "Argument 8";
string s9 = "Argument 9";

string result = string.Empty;
object[] data = new object[] { s1, s2, s3, s4, s5, s6, s7, s8, s9 };
Stopwatch sw = new Stopwatch();
sw.Start();
for(int x = 0; x < 100000; x++)
    result = string.Format("{0},{1},{2},{3},{4},{5},{6},{7},{8}", data);
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

StringBuilder sb = new StringBuilder();
sw = new Stopwatch();
sw.Start();
for (int x = 0; x < 100000; x++)
{
    sb.Length = 0;
    sb.AppendFormat("{0},{1},{2},{3},{4},{5},{6},{7},{8}", data);
    result = sb.ToString();
}
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

String.Format在其实现中使用了StringBuilder,所以你不能说哪个更好。