Use the StringBuilder class to concatenate strings quickly in C#

In my previous example Generate random strings in C#, I used code similar to the following to generate a random string of letters.

// Make a word.
string word = "";
for (int j = 1; j <= num_letters; j++)
{
// Pick a random number between 0 and 25
// to select a letter from the letters array.
int letter_num = rand.Next(0, letters.Length - 1);

// Append the letter.
word += letters[letter_num];
}

It may look like this code creates a single string but actually as it builds its result it creates a whole bunch of strings. For reasons of its own, .NET strings are immutable. That means you can never modify a string. Your code may look like it modifies a string but internally .NET destroys the old string and creates a new one.

In this example if num_letters is 10, then this code actually creates 11 strings. It starts with an empty string and adds the 10 letters one at a time, creating a new string each time.

The .NET Framework is optimized to make creating and destroying lots of strings reasonably fast but it still takes more time than it would if strings were implemented as simple arrays of characters.

The StringBuilder class manages a buffer of characters without turning them into a string so it can perform operations such as appending text more quickly than .NET can create a new string.

The following code does the same thing as the previous version except it use a StringBuilder instead of using += to concatenate letters to its strings.

// Make a word.
StringBuilder string_builder = new StringBuilder();
for (int j = 1; j <= num_letters; j++)
{
// Pick a random number between 0 and 25
// to select a letter from the letters array.
int letter_num = rand.Next(0, letters.Length - 1);

// Append the letter.
string_builder.Append(letters[letter_num]);
}

// Add the word to the list.
words[i] = string_builder.ToString();

There is some overhead to creating a StringBuilder object so it's not always faster. The class is most useful when you need to perform a very large number of operations on strings.

Note that both the += and StringBuilder methods are very fast. In the example shown in the picture, the "slow" += method took around 3.5 seconds to generate 1 million strings while StringBuilder took around 1.9 seconds. That means using StringBuilder saved only about 1.6 microseconds per string.

The moral is that you should generally use whichever method you find least confusing unless you're performing a huge number of string operations. I find += easier to read so I use it most of the time.

   

 

What did you think of this article?




Trackbacks
  • No trackbacks exist for this post.
Comments

  • 5/31/2010 8:36 AM Raj wrote:
    This is just FYI if you are planning to move a classic ASP app from IIS5 to IIS6 and use +=:

    When using += in Classic ASP (3.0?; not .NET) apps, when moved from IIS 5.0 to IIS 6.0, the asp worker process would reach its 2 GB limit and the site would crash after using the app for sometime, requiring IIS Reset. We replaced every instance of += with a MS provided StringBuilder.vbs script, which helped resolve asp worker process from reaching its 2 GB limit. += worked fine in IIS 5.0 for classic ASP.
    Reply to this
Leave a comment

Submitted comments are subject to moderation before being displayed.

 Name

 Email (will not be published)

 Website

Your comment is 0 characters limited to 3000 characters.