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. 


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)

    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.




©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页