String vs StringBuilder

In this section there are some examples and benefits to choose between the String or StringBuilder class.

Description

Both represent sequences characters in .NET. However:

  • String is immutable

    • Each operation that appears to modify a string actually creates a new string object that contains the modification.

  • StringBuilder is mutable

    • Once an instance of the class has been created, it can be modified by appending, removing, replacing, or inserting characters. The new memory is allocated when the current capacity is exceeded until it reaches the MaxCapacity property of the StringBuilder (by default Int32.MaxValue = 2147483647, that is 2GB).

Because strings are immutable, string manipulation routines that perform repeated modifications to what appears to be a single string can exact a significant performance penalty. In these cases, the StringBuilder class generally offers better performance.

Using String

Random rnd = new Random();
string str = String.Empty;

for (int ctr = 0; ctr <= 1000000; ctr++)
{
    str += Convert.ToChar(rnd.Next(97, 122));
    if (str.Length % 30 == 0)
        str += Environment.NewLine;
}

this.ResultTextBox.Text = str;

Using StringBuilder

Random rnd = new Random();
StringBuilder sb = new StringBuilder();

for (int ctr = 0; ctr <= 1000000; ctr++)
{
    sb.Append(Convert.ToChar(rnd.next(97,122)));
    if (sb.Length % 30 == 0)
        sb.AppendLine();
}

this.ResultTextBox.Text = sb.ToString();

Performance

Do not replace StringBuilder whenever you want to manipulate strings. Performance depends on the size of the string, the amount of memory for the new string, and the operation which is executing. Testing is needed to determine if StringBuilder offers a significant performance improvement.

Use the String class when:

  • The number of changes to a string is small. In these cases, StringBuilder might offer little or no performance improvement over String.

  • You are performing a fixed number of concatenation operations, particularly with string literals. In this case, the compiler might combine the concatenation operations into a single operation.

  • You have to perform extensive search operations while you are building your string. The StringBuilder class lacks search methods such as IndexOf or StartsWith. You will have to convert the StringBuilder object to a String for these operations, and this can negate the performance benefit from using StringBuilder.

Use the StringBuilder class when:

  • The number of changes to a string is unknown at design time, for example, when you are using a loop to concatenate a random number of strings that contain user inputs.

  • You expect to make a significant number of changes to a string.

Last updated