连接字符串最有效的方法是什么?


当前回答

除了其他答案之外,请记住StringBuilder可以被告知要分配的初始内存量。

容量参数定义了当前实例分配的内存中可以存储的最大字符数。它的值被赋给Capacity属性。如果当前实例中存储的字符数量超过了这个容量值,StringBuilder对象就会分配额外的内存来存储这些字符。 如果容量为零,则使用特定于实现的默认容量。

重复添加到未预先分配的StringBuilder可能会导致大量不必要的分配,就像重复连接常规字符串一样。

If you know how long the final string will be, can trivially calculate it, or can make an educated guess about the common case (allocating too much isn't necessarily a bad thing), you should be providing this information to the constructor or the Capacity property. Especially when running performance tests to compare StringBuilder with other methods like String.Concat, which do the same thing internally. Any test you see online which doesn't include StringBuilder pre-allocation in its comparisons is wrong.

如果你无法猜测它的大小,你可能在写一个效用函数它应该有自己的可选参数来控制预分配。

其他回答

最有效的方法是使用StringBuilder,如下所示:

StringBuilder sb = new StringBuilder();
sb.Append("string1");
sb.Append("string2");
...etc...
String strResult = sb.ToString();

@jonezy:字符串。Concat是好的,如果你有一些小东西。但是,如果您正在连接兆字节的数据,那么您的程序可能会崩溃。

StringBuilder.Append()方法比使用+操作符要好得多。但我发现,当执行1000个或更少的连接时,String.Join()甚至比StringBuilder更有效。

StringBuilder sb = new StringBuilder();
sb.Append(someString);

String的唯一问题。Join是指必须使用公共分隔符连接字符串。

编辑:正如@ryanversaw指出的,可以将分隔符设置为string.Empty。

string key = String.Join("_", new String[] 
{ "Customers_Contacts", customerID, database, SessionID });

另一个解决方案:

在循环中,使用List而不是string。

List<string> lst= new List<string>();

for(int i=0; i<100000; i++){
    ...........
    lst.Add(...);
}
return String.Join("", lst.ToArray());;

它非常非常快。

. net性能专家Rico Mariani有一篇关于这个主题的文章。这并不像人们想象的那么简单。基本的建议是:

如果你的图案是这样的: X = f1(…)+ f2(…)+ f3(…)+ f4(…) 这是一个concat,它是活泼的,StringBuilder可能不会有帮助。 如果你的图案是这样的: 如果(…)x += f1(…) 如果(…)x += f2(…) 如果(…)x += f3(…) 如果(…)x += f4(…) 那么你可能需要StringBuilder。

另一篇支持这一说法的文章来自Eric Lippert,他详细描述了在一行+连接上执行的优化。

对于只有两个字符串,您肯定不希望使用StringBuilder。如果超过某个阈值,StringBuilder开销将小于分配多个字符串的开销。

所以,对于超过2-3个字符串,使用DannySmurf的代码。否则,只需使用+运算符。