#63 – Use StringBuilder for More Efficient String Concatentation

Using the concatenation operator (+) for string concatenation is convenient, but can be inefficient because a new string is allocated for each concatenation.

Let’s say that we do a simple test, appending the string equivalents of the first 50,000 integers:

string s1 = "";
for (int i = 0; i < 50000; i++)
    s1 = s1 + i.ToString();

In one test environment, this loop took 30,430 milliseconds.

We can make this code more efficient by using the Append method of the StringBuilder class, which avoids allocating memory for the string on each iteration:

 StringBuilder sb = new StringBuilder("");
 for (int i = 0; i < 50000; i++)

In the same test environment as before, this version takes 6 milliseconds.

StringBuilder is definitely more efficient, but likely worth using only when you plan on doing a large number of string concatenations.  See also Concatenating Strings Efficiently.


#62 – String Concatenation

In C#, you can use the ‘+’ (plus) character to concatenate multiple strings together.

 string s1 = "C#";
 string s2 = "fun";
 string s3 = s1 + " is " + s2;   // "C# is fun"

You can use one or more concatenation operators in the same expression and you can use an expression containing the concatenation operator anywhere that a string value is expected.

You can also use String.Concat or String.Format to concatenate strings.

 // Concat method
 string s4 = String.Concat(new object[] { "The ", 3, " musketeers" });
 string s5 = String.Concat("This", "That");    // ThisThat

 // Use String.Format to concatenate
 string s6 = string.Format("{0}{1}{2}", s1, " is ", s2);