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

时间:2020-03-05 18:41:46  来源:igfitidea点击:

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

解决方案

回答

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

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

@jonezy:如果我们有一些小东西,String.Concat很好。但是,如果要串联兆字节的数据,则程序可能会崩溃。

回答

StringBuilder.Append()方法比使用+运算符要好得多。但是我发现,当执行1000个或者更少的串联时,String.Join()甚至比StringBuilder更有效。

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

String.Join的唯一问题是我们必须使用通用的定界符将字符串连接起来。 (编辑:)如@ryanversaw所指出的,我们可以使定界符字符串为空。

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

回答

对于仅两个字符串,我们绝对不希望使用StringBuilder。在某个阈值之上,StringBuilder的开销小于分配多个字符串的开销。

因此,对于2-3个以上的字符串,请使用DannySmurf的代码。否则,只需使用+运算符。

回答

从Chinh开始,StringBuilder并不总是更快:

经验法则

  • 当串联三个或者三个以下的动态字符串值时,请使用传统的字符串串联。
  • 当连接三个以上的动态字符串值时,请使用StringBuilder。
  • 从多个字符串文字构建大字符串时,请使用@字符串文字或者inline +运算符。

在大多数情况下,StringBuilder是我们最好的选择,但是在该帖子中显示的情况下,我们至少应考虑每种情况。

回答

这将取决于代码。
通常,StringBuilder效率更高,但是如果我们仅连接几个字符串并在一行中完成所有操作,则代码优化可能会为我们解决这个问题。考虑代码的外观也很重要:对于较大的集合,StringBuilder将使其更易于阅读,对于较小的集合,StringBuilder将仅添加不必要的混乱。

回答

如果我们在循环中操作,StringBuilder可能是理想选择。这样可以节省我们定期创建新字符串的开销。在只运行一次的代码中,String.Concat可能很好。

但是,Rico Mariani(.NET优化专家)编了一个测验,最后他说,在大多数情况下,他建议使用String.Format。

回答

.NET Performance专家Rico Mariani在此主题上发表了一篇文章。这并不像人们所想的那么简单。基本建议是这样的:

If your pattern looks like:
  
  x = f1(...) + f2(...) + f3(...) + f4(...)
  
  that's one concat and it's zippy, StringBuilder probably won't help.
  
  If your pattern looks like:  
  
  if (...) x += f1(...)

  if (...) x += f2(...)

  if (...) x += f3(...)

  if (...) x += f4(...)  
  
  then you probably want StringBuilder.

支持该说法的另一篇文章来自埃里克·利珀特(Eric Lippert),他详细描述了在一行" +"串联上执行的优化。

回答

从这篇MSDN文章中:

There is some overhead associated with
  creating a StringBuilder object, both
  in time and memory. On a machine with
  fast memory, a StringBuilder becomes
  worthwhile if you're doing about five
  operations. As a rule of thumb, I
  would say 10 or more string operations
  is a justification for the overhead on
  any machine, even a slower one.

因此,如果我们必须执行十个以上的字符串操作/串联操作,那么如果我们信任MSDN,请选择StringBuilder,否则使用'+'的简单字符串concat即可。