#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++)
     sb.Append(i.ToString());

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.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

One Response to #63 – Use StringBuilder for More Efficient String Concatentation

  1. Pingback: #69 – Strings Are Immutable « 2,000 Things You Should Know About C#

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: