StringBuilder class in C#

When I learn to program, I remember that my professor told me that the String class is immutable. That means you cannot change the memory of that string. Every time you try to modify a string, a new memory allocation happens.

string initialString = "Joe"; // the initialString pointer points to 0x00000269b2b1b978
initialString = initialString.Replace("e", "hn"); // Now the initialString pointer points to 0x00000269b2b1c750

Use StringBuilder instead of String operators

When I was a junior programmer, every time when I have needed to concatenate two strings, I have used the string operators. I was all wrong.

const string logFilePath = @"C:\Users\valen\Desktop\logs release.txt";
string[] paragraphs = File.ReadAllLines(logFilePath);

string text = "";
for (int i = 0; i < paragraphs.Length; i++)
{
text += paragraphs[i].Replace((i + 1) + ".", "");
}
Console.WriteLine(text);

The above code is not efficient because it allocates for every iteration an unnecessary instance. As a result, the Garbage Collector will have a lot of work to do.

The alternative is to use a mutable class, which is design for operations like this. In the C# language, there is the StringBuilder class.

StringBuilder text = new StringBuilder();

for (int i = 0; i < paragraphs.Length; i++)
{
	text.Append(paragraphs[i].Replace((i + 1) + ".", ""));
}
Console.WriteLine(text);

StringBuilder class has a mutable array internally. That’s why one of the constructors takes the argument capacity. It’s optional, but it’s better to use it if you know approximately what will be the length of the string. So, the Length property returns you how many chars has the string, and the Capacity gives you the current capacity of the builder.

The string builder is useful when you want to append in a loop. If you only have some operations, don’t bother to use it.

The StringBuilder is not thread-safe, so be careful if you use it in Parallel.Foreach.

Leave a Comment