C# 使用string.Format和许多参数:string或StringBuilder时,什么性能更好?

C# 使用string.Format和许多参数:string或StringBuilder时,什么性能更好?,c#,string,stringbuilder,C#,String,Stringbuilder,使用string.Format执行以下操作: string.Format(txt, arg0, arg1, arg2, arg3, arg4,...) 与表示txt+=args相同因此,它每次从args列表中附加新字符串时都会创建新对象?最好使用StringBuilder.Format?如果只使用字符串格式,请使用string.Format。 如果使用大量字符串和/或字符串形式的串联,请使用StringBuilder 看看这个: 我上面的评论意味着您应该在您的环境中测试您的性能。使用秒表实例,

使用
string.Format
执行以下操作:

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

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

如果只使用字符串格式,请使用string.Format。 如果使用大量字符串和/或字符串形式的串联,请使用StringBuilder

看看这个:

我上面的评论意味着您应该在您的环境中测试您的性能。使用秒表实例,创建一个循环,该循环在string.Format和StringBuilder.AppendFormat上运行至少十万次,然后在Stopwatch.elapsedmillesons中测量值。这将大致为您提供差异的概念

在矿山环境中,这两种方法是完全相同的。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 s1=“参数1”;
string s2=“参数2”;
string s3=“参数3”;
string s4=“参数4”;
string s5=“参数5”;
字符串s6=“参数6”;
字符串s7=“参数7”;
字符串s8=“参数8”;
字符串s9=“参数9”;
字符串结果=string.Empty;
对象[]数据=新对象[]{s1、s2、s3、s4、s5、s6、s7、s8、s9};
秒表sw=新秒表();
sw.Start();
对于(int x=0;x<100000;x++)
result=string.Format(“{0},{1},{2},{3},{4},{5},{6},{7},{8}”,数据);
sw.Stop();
控制台写入线(软件延迟毫秒);
StringBuilder sb=新的StringBuilder();
sw=新秒表();
sw.Start();
对于(int x=0;x<100000;x++)
{
sb.长度=0;
sb.AppendFormat(“{0}、{1}、{2}、{3}、{4}、{5}、{6}、{7}、{8}”,数据);
结果=sb.ToString();
}
sw.Stop();
控制台写入线(软件延迟毫秒);

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

为什么不呢?您的意思是尝试这样做:
String st=“”;对于(inti=0;i<9000;i++){st+=“dop”}
它太快了!虽然这是一个灾难性的循环,为什么?因为它创建了9000个对象。如何知道
StringBuilder.Format
是否通过测试传播对象?!当你有这样一个问题的时候,看看第一个。StringBuilderCache应该能让您相信框架代码并不糟糕,也不需要您的帮助。是否有办法在运行时查看由
string+=
创建的对象?不清楚。你在说什么东西?字符串是不可变的,因此每次调用+=运算符时,都会使用变量的上一个值加上添加的字符串创建一个新字符串。然后将新字符串指定给变量。