This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

.NET Framework
.NET 1.1+

The StringBuilder Class

Creating strings with the use of multiple concatenation operations can lead to low performance and wasteful memory usage. The StringBuilder class allows strings to be created and updated without the problems caused by the immutability of the String class.

What is a StringBuilder?

Objects of the String class are immutable. That is, once created in memory, a string instance cannot be modified. In order for a string to appear changeable, every modification to its contents causes a new object to be generated, using addition memory and, potentially, lowering the performance of an application.

The StringBuilder class provides string-like functionality by storing a mutable series of characters. These individual characters can be read and modified via an indexer. The contents can also be changed using concatenation, insertion and deletion methods. Once any building process is complete, the contents can be extracted to a string for further use.

One of the primary uses of StringBuilder is for multiple concatenation operations, especially when the modifications occur within a large loop. StringBuilders generally give better performance and a lower memory footprint when working with large strings or when the number of concatenations is variable. For low and fixed numbers of concatenations, particularly when not within a loop, simple strings can give better performance.

Using StringBuilders

In this article we will demonstrate the key methods and properties of the StringBuilder class with simple examples. To follow the examples create a new console application project. As the StringBuilder class is found in the System.Text namespace, ensure that the following using directive is present in the class file. All of the examples that follow can be tested using the Main method of the project.

using System.Text;

Creating a StringBuilder

The StringBuilder class includes six constructors, including a default constructor that requires no arguments. The default constructor creates a new StringBuilder object that contains an empty string. We can see this by using the ToString method, which returns the StringBuilder's contents as a string.

StringBuilder sb = new StringBuilder();
Console.WriteLine(sb.ToString() == string.Empty);   // Outputs "True"

When a StringBuilder object is instantiated, a capacity for the contents is determined and memory is allocated. When using the basic constructor, the capacity is set to a default value. If the size of the string within the StringBuilder exceeds this capacity, the available size is increased automatically. This can lead to the allocated of more memory than is required. To minimise this possibility, you can elect to specify the initial capacity of a StringBuilder with a single integer parameter. If the parameter is zero, the default capacity is used.

The following sample initialises the capacity to fifty characters:

StringBuilder sb = new StringBuilder(50);

It is possible to specify a maximum capacity for a StringBuilder object. The default maximum size is 2,147,483,647 characters. If the maximum capacity is exceeded, an exception is thrown. To specify the capacity and maximum capacity you can use a constructor that accepts two integer parameters.

The following creates a StringBuilder with an initial capacity of fifty characters and a maximum size of two hundred characters:

StringBuilder sb = new StringBuilder(50, 200);

Each of the three constructors described above initialises a StringBuilder with an empty string. The remaining three constructors can be used when you wish to set the contents during instantiation. The simplest accepts a string as its only argument. The string is used as the initial content of the new object. The default capacity is used for the StringBuilder, though this may be immediately increased if the capacity is insufficient for the supplied contents. If the initial string is null, the StringBuilder will contain an empty string.

StringBuilder sb = new StringBuilder("BlackWasp");
Console.WriteLine(sb);                              // Outputs "BlackWasp"

sb = new StringBuilder();
Console.WriteLine(sb.ToString() == string.Empty);   // Outputs "True"

To set the contents and the initial capacity, specify the capacity as the second argument:

StringBuilder sb = new StringBuilder("BlackWasp", 50);

The final constructor initialises the contents of the new StringBuilder using a substring of an existing string. The first parameter is the string from which to extract some text. The second and third parameters define the starting point and the number of characters to use. A fourth parameter specifies the starting capacity of the object.

string aString = "The quick brown fox.";
StringBuilder sb = new StringBuilder(aString, 4, 5, 50);
Console.WriteLine(sb);  // Outputs "quick"
25 October 2009