S. Valmont
S. Valmont

Reputation: 1031

Fixed Number of .NET String Concatenations

"...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 arbitrary 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.

Upvotes: 0

Views: 70

Answers (3)

aepheus
aepheus

Reputation: 8197

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.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1064204

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.

Upvotes: 2

robbrit
robbrit

Reputation: 17960

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.

Upvotes: 0

Related Questions