差异字符串连接性能 [英] Difference in String concatenation performance

查看:185
本文介绍了差异字符串连接性能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道你应该使用的StringBuilder 连接字符串,但我只是想知道如果有一个串联字符串变量和字符串文字的差异时。那么,有没有在性能上建设S1,S2和S3有区别吗?

 字符串FOO =富;
串吧=酒吧;

字符串S1 =富+酒吧;
字符串s2 = FOO +酒吧;
串S = foo的+吧;
 

解决方案

在这种情况下,你present,它实际上最好使用连接运算符的字符串类。这是因为它可以pre-计算字符串的长度和分配缓冲一次,做内存的快速复制到新的字符串缓冲区。

这是用于连接字符串的一般规则。如果您有要连接在一起的项目集数(无论是2或2000等),最好是只将它们连接所有的连接操作符,像这样:

 字符串结果= S1 + S2 + ... + SN;
 

应该注意到在您的具体情况为S1:

 字符串S1 =富+酒吧;
 

编译器发现它可以优化字符串这里的串联和转换到上述这样的:

 字符串S1 =foobar的;
 

请注意,这只是针对两个字符串连接到一起。所以,如果你做到这一点:

 字符串s2 = FOO +一+吧;
 

随后,它没有什么特别的(但它仍然将调用Concat的和precomputes的长度)。然而,在这种情况下:

 字符串s2 = FOO +一+反璞归真+吧;
 

编译器将它转换成:

 字符串s2 = FOO +另一个+吧;
 

如果您正在串联串的个数是可变的(如在,一个环路不预先知道多少元素有在它),那么StringBuilder的是那些串联串的最有效的方式,作为你总是要reallcate缓冲区占添加新的字符串项(其中,你不知道有多少是左)。

I know you should use a StringBuilder when concatenating strings but I was just wondering if there is a difference in concatenating string variables and string literals. So, is there a difference in performance in building s1, s2, and s3?

string foo = "foo";
string bar = "bar";

string s1 = "foo" + "bar";
string s2 = foo + "bar";
string s3 = foo + bar;

解决方案

In the case you present, it's actually better to use the concatenation operator on the string class. This is because it can pre-compute the lengths of the strings and allocate the buffer once and do a fast copy of the memory into the new string buffer.

And this is the general rule for concatenating strings. When you have a set number of items that you want to concatenate together (be it 2, or 2000, etc) it's better to just concatenate them all with the concatenation operator like so:

string result = s1 + s2 + ... + sn;

It should be noted in your specific case for s1:

string s1 = "foo" + "bar";

The compiler sees that it can optimize the concatenation of string literals here and transforms the above into this:

string s1 = "foobar";

Note, this is only for the concatenation of two string literals together. So if you were to do this:

string s2 = foo + "a" + bar;

Then it does nothing special (but it still makes a call to Concat and precomputes the length). However, in this case:

string s2 = foo + "a" + "nother" + bar;

The compiler will translate that into:

string s2 = foo + "another" + bar;

If the number of strings that you are concatenating is variable (as in, a loop which you don't know beforehand how many elements there are in it), then the StringBuilder is the most efficient way of concatenating those strings, as you will always have to reallcate the buffer to account for the new string entries being added (of which you don't know how many are left).

这篇关于差异字符串连接性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆