Search code examples
.netstringconcatenationstringbuilderfixed

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.


Solution

  • 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.