C# StringBuilder

The System.String class can use the + operator to concatenate two strings. But this is inefficient when concatenating two different strings. The reason is that String objects in .NET are immutable, that is, the value cannot be changed once it is assigned to the stringvariable. When you concatenate another string to an existing one, you discard its old value and create a brand new string object which contains the result of the concatenation. Repeating this process several times leads to a performance penalty as new temporary objects will be created and old objects will be discarded.

Consider the following example, where you concatenate all the numbers from 0 to 9999;

int counter = 9999;
string s = string.Empty;

for (int i = 0; i <= counter; i++) 
{
   s += i.ToString();
}
Console.WriteLine(s);

You might see no problem just by looking at the code but if we use the Stopwatch object to time the operation, you can see how long it takes to do the operations. Modify the code as shown here:

int counter = 9999;
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();

string s = string.Empty;

for (int i = 0; i <= counter; i++) 
{
   s += i.ToString();
}

sw.Stop();
Console.WriteLine(s);
Console.WriteLine("Took {0} ms", sw.ElapsedMilliseconds);

We used the Stopwatch class’ Start() method to start the timer, and then proceed to the loop. After finishing the loop, we call the Stop() method of the Stopwatch class. On average, it took about 374 ms to run this application. Let’s now use the StringBuilder class in .NET to perform the string concatenation, using its Append() method and demonstrate the performance improvement:

int counter = 9999;
System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
sw.Start();

StringBuilder sb = new StringBuilder();

for (int i = 0; i <= counter; i++) 
{
   sb.Append(i.ToString());
}

sw.Stop();
Console.WriteLine(sb.ToString());
Console.WriteLine("Took {0} ms", sw.ElapsedMilliseconds);

This time, it took about 3 ms to perform this operation. As you can see, the performance has improved dramatically. Performance can still be greater if the loop variant is increased. The StringBuilder is great if you’re concatenating strings with large amount of text, such as the content of a document. The StringBuilder class contains some important methods, which are shown in the following table.

Method Description
Append Appends the string representation of a specified object to the end of this instance.
AppendFormat Appends a formatted string, which contains zero or more format specifiers, to this instance. Each format specification is replaced by the string representation of corresponding object argument.
AppendLine Appends the default line terminator, or a copy of a specified string and the default line terminator, to the end of this instance.
CopyTo Copies the characters from a specified segment of this instance to a specified segment of a destination Char array.
Insert Inserts the string representation of a specified object into this instance at a specified character position.
Remove Removes the specified range of characters from this instance.
Replace Replaces all occurrences of a specified character or string in this instance with another specified character or string.
ToString Converts the value of a StringBuilder to a String.