The StringBuilder Class

Henrique Siebert Domareski
6 min readAug 4, 2020

--

String

A string in C# is an object of type String, whose value is a text. Internally, the text is stored as a sequential ready-only collection of Char objects. A string has a Length property that shows the number of Char objects it contains.

String is a reference type that looks like value type (for example, the equality operators == and != are overloaded to compare on value, not on reference).

In .NET, the string keyword (in lower case) is an alias for String (in capital case). So you can use any one of them and they will work in the same way. The String class provides many methods for safely creating, manipulating, and comparing strings

Why and when should we use the StringBuilder Class?

Strings objects are immutable. It means that these objects cannot be changed after they have been created. The methods and operators that appear to modify a string actually they delete the old string and create a new similar to the old one with the appropriate changes that were made.

Despite that, the operations with string in .NET are highly optimized, so in most cases working with string will not have an impact on the performance of the application. But let’s suppose that we have some looping functions that are executed hundreds or thousands of times and deal with string operations, in this case, the performance will be affected because it will drop and recreate new objects a lot of time, and this can be an issue. To avoid this problem we can work with the StringBuilder class.

The StringBuilder is a mutable string class, which means that once an instance of the class has been created, it can be modified by appending, removing, replacing, or inserting characters. The StringBuilder class works with a buffer that provides better performance in these situations where it’s necessary to deal with a lot of string manipulation.

The StringBuilder instead of dropping and recreating the objects, it will go into the buffer and do the necessary changes. A StringBuilder object maintains a buffer to accommodate expansions to the string, so what will happen behind the scenes is that the new data will be appended to the buffer if room is available, otherwise, a new larger buffer is allocated, the data from the original buffer will be copied to the new buffer, and the new data is then appended to the new buffer.

StringBuilder does not always give better performance. For situations where you have a limited number of strings, the compiler can optimize this and combine individual concatenation operations into a single operation.

But there is something that we need to keep in mind:

Although the StringBuilder class generally offers better performance than the String class, you should not automatically replace String with StringBuilder whenever you want to manipulate strings. Performance depends on the size of the string, the amount of memory to be allocated for the new string, the system on which your app is executing, and the type of operation. You should be prepared to test your app to determine whether StringBuilder actually offers a significant performance improvement.

There are some conditions that you can check to know when you should consider using the String class or the StringBuilder class. Those conditions I got from the Microsoft official documentation.

Consider using the String class under these conditions:

  • When the number of changes that your app will make to a string is small. In these cases, StringBuilder might offer negligible or no performance improvement over String.
  • When 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.
  • When 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’ll have to convert the StringBuilder object to a String for these operations, and this can negate the performance benefit from using StringBuilder.

Consider using the StringBuilder class under these conditions:

  • When you expect your app to make an unknown number of changes to a string at design time (for example, when you are using a loop to concatenate a random number of strings that contain user input).
  • When you expect your app to make a significant number of changes to a string.

The StringBuilder class can be used when you are working with strings in a tight loop. Instead of creating a new string over and over again, you can use the StringBuilder, which uses a string buffer internally to improve performance.

Let’s go to the code!

I’ve created a console application to show some cases of how we can work with string and the StringBuilder class.

String example

This is an example of concatenation without using the StringBuilder class:

string s = "Example of ";
s = s + "string concatenation";
Console.WriteLine(s);

The output of this code will be:

Example of string concatenation

What is happening behind the scenes is that the original object was removed and it was created a new object with the concatenated value. For this case, it’s not a problem because it’s just a small operation, but let’s suppose that we have this scenario:

string s = string.Empty;for (int i = 0; i < 10000; i++)
{
s += "x";
}

This code will run 10.000 times, and for each time it will create a new string. This can be a problem because those operations will affect the performance of the application. In the next topic, we will see a better solution for this situation, through the use of the StringBuilder class.

StringBuilder Class

When working with a large number of string operations, .NET offer some special helper classes when dealing with strings, one of them is the StringBuilder.

The StringBuilder is not immutable, this means that when we do some operation using StringBuilder, it will not drop and recreate the object.

StringBuilder examples

In the same console application I will add the import to work with the StringBuilder class:

using System.Text;

The Append Method

To concatenate values now we are going to use the Append method from the StringBuilder class:

StringBuilder sb = new StringBuilder("Example of ");
sb.Append("string concatenation");
Console.WriteLine(sb);

The result of this will be:

Example of string concatenation

In this scenario, what is happening behind the scenes is that the actual value was appended to the current string.

We can use the StringBuilder to execute the same loop that we saw in the previous topic, but now using this class it will be executed faster:

StringBuilder sb = new StringBuilder(string.Empty);for (int i = 0; i < 10000; i++)
{
sb.Append("x");
}

For this situation, it’s better to use the StringBuilder because then it will not drop and create a new object 10.000 times, but it will use the string buffer internally, which will improve the performance of your code.

The AppendLine Method

You can use the method AppendLine to add a new line in the text, for example:

StringBuilder sb = new StringBuilder("Example of ");
sb.Append("string concatenation");
Console.WriteLine(sb);
sb.AppendLine();
sb.AppendLine(" using StringBuilder");
Console.WriteLine(sb);

This will be printed like this:

Example of string concatenation
using StringBuilder

The Replace Method

You can use the replace method to replace some text:

StringBuilder sb = new StringBuilder("Example of ");
sb.Append("string concatenation with StringBuilder");
sb.Replace("StringBuilder", "the StringBuilder class");
Console.WriteLine(sb);

The output of this code will be:

Example of string concatenation with the StringBuilder class

Note that to use the Replace, the text should be exactly the same. So if you try to replace the text ‘StringBuilder’ but type ‘Stringbuilder’ (with the letter ‘b’ in lower case), the value will not be changed:

StringBuilder sb = new StringBuilder("Example of ");
sb.Append("string concatenation with StringBuilder");
sb.Replace("Stringbuilder", "the StringBuilder class");
Console.WriteLine(sb);

The output of this code will be:

Example of string concatenation with StringBuilder

Note that despite of not find the text ‘Stringbuilder’, it will not throw any kind of error, it will just do not change the text.

There are others methods from the StringBuilder class that can be used, you can read more about it in the official Microsoft documentation clicking here.

Conclusion

For situations where you do not have many strings to deal with, you should consider just do the operations without using the StringBuilder class. But in scenarios where you need to deal with a big quantity of strings, you should consider using the StringBuilder class because this will have a positive impact on the performance of your application and definitely this is a better choice.

Thanks for reading!

References

Strings (C# Programming Guide)

Programming in C# — Exam Ref 70–483 — Rob Miles

--

--

No responses yet