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