Ways to Clear a C# Stringbuilder Obejct

Before .NET 4.0 there was no explicit method to clear a C# StringBuilder object.

We had to resort to one of three approaches:

1. Remove from the start of the StringBuilder by its length:

myStringBuilder.Remove(0, myStringBuilder.Length);

2. Store the contents in another string and call Replace upon the stringbuilder using the string as a parameter:

string s = myStringBuilder.ToString();
myStringBuilder.Replace(s, "");

3. Or simply just set the Length property to zero. This property is not read-only.

myStringBuilder.Length = 0;

But which is the fastest? Crude (and in no way scientific) tests on my laptop at home gave the following results when looping round this operation 50 million times. All numers are in milliseconds:

1. 5585,    5601,     6037
2. 14945,   14679,    15094
3. 4898,    4805,     5023
 

So there we have it. Setting the Length directly was the best C# .NET 4.0 But all this is immaterial if you are using C# .NET 4.0, as Microsoft have kindly extended the StringBuilder obect to include the Clear method: http://blogs.msdn.com/wriju/archive/2010/03/01/net-framework-4-0-newbie-stringbuilder-new.aspx But what of its relative performance?

5772,   5476,   5226

So, it would seem from my crude and unscientific tests that for C# 4, the quickest way to clear a StringBuilder object is actually avoid the inbuilt Clear method, and set the length directly to zero.

I’ve put the sample code here so that you can test it for yourself:

ClearStringBuilder.cs

Leave a Reply