StringBuilder Class in C#

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

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, I used string operators whenever I needed to concatenate two strings. 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 inefficient because it allocates an unnecessary instance for every iteration. As a result, the Garbage Collector will have a lot of work to do.

The alternative is to use a mutable class, which is designed 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 the length of the string. So, the Length property returns how many chars the string has, and the Capacity gives you the current capacity of the builder.

The string builder is helpful 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