开发者

Fixed Number of .NET String Concatenations

开发者 https://www.devze.com 2023-03-23 09:50 出处:网络
\"...the String class is preferable for a concatenation operation if a fixed number of String objects are concatenated. In that case, the individual concatenation operations might even be combined int

"...the String class is preferable for a concatenation operation if a fixed number of String objects are concatenated. In that case, the individual concatenation operations might even be combined into a single operation by the compiler.

A StringBuilder object is preferable for a concatenation operation if an arb开发者_JAVA技巧itrary number of strings are concatenated..."

http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx

Thing that gets me are the uncertain words "might even be" in the first paragraph. Shouldn't it be "surely will"? Because without combining the concatenations into one operation, the repeated memory allocation of String would render it absolutely inferior to StringBuilder.


Well, it could also be no noticeable difference. To be honest, they'll be ridiculously close for trivial concatenations, but: for a straight concatenation of "n" strings in one operation, Concat (aka +) will shine; the length etc can be calculated efficiently, and then it is just the copying. In a loop, StringBuilder will shine.

When you Concat in one operation:

string s = a + b + c + x + y + z;

That is really:

string s = string.Concat(a, b, c, x, y, z);

Which is one extra string only.


It's saying that if the length of the string can be determined at compile time, the compiler will automatically merge it for you into a more efficient representation. However if the length can't be calculated at compile time you should use a StringBuilder.

The "might even be" is if you're only concatenating two strings of uncertain length, it might be faster just to use String. The more strings being concatenated, the more the benefit of a StringBuilder.


My guess is you could write code in a way that the compiler would not combine it into one. But, if you write code the way microsoft want you to, it should do it in one operation.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号