C#字符串连接消耗

来源:互联网 发布:淘宝客推广平台有哪些 编辑:程序博客网 时间:2024/06/05 07:47

1、Concatenation is the process of appending one string to the end of another string. When you concatenate string literals or string constants by using the + operator, the compiler creates a single string. No run time concatenation occurs. However, string variables can be concatenated only at run time. In this case, you should understand the performance implications of the various approaches.


2、If you are not concatenating large numbers of strings (for example, in a loop), the performance cost of this code is probably not significant. The same is true for the String.Concat and String.Format methods.

However, when performance is important, you should always use the StringBuilder class to concatenate strings. 

3、

This is the most interesting test because we have several options here. We can concatenate strings with +, String.ConcatString.Join and StringBuilder.Append.

Screenshot - StringConcat.JPG
string Add(params string[] strings) // Used Test functions for this chart{    string ret = String.Empty;        foreach (string str in strings)        ret += str;    return ret;}string Concat(params string[] strings){    return String.Concat(strings);}string StringBuilderAppend(params string[] strings){    StringBuilder sb = new StringBuilder();    foreach (string str in strings)        sb.Append(str);    return sb.ToString();}string Join(params string[] strings){    return String.Join(String.Empty, strings);}

And the winner for String Concatenation is ... Not string builder but String.Join? After taking a deep look with Reflector I found that String.Join has the most efficient algorithm implemented which allocates in the first pass the final buffer size and then memcopy each string into the just allocated buffer. This is simply unbeatable. StringBuilder does become better above 7 strings compared to the + operator but this is not really code one would see very often.


参考:

1、https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/strings/how-to-concatenate-multiple-strings

2、https://www.codeproject.com/Articles/14936/StringBuilder-vs-String-Fast-String-Operations-wit