xak的专栏

Sometimes when I look at the world, I can see a line behind it.

C#字符串连接消耗

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

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cubesky/article/details/78230390
个人分类: 基础知识
想对作者说点什么? 我来说一句

c# string操作,去除重复的串

2011年07月26日 38KB 下载

MakeAString

2013年11月25日 30KB 下载

没有更多推荐了,返回首页

不良信息举报

C#字符串连接消耗

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭