best way to clear contents of .NET's StringBuilder

Viewed 76896

I would like to ask what you think is the best way (lasts less / consumes less resources) to clear the contents in order to reuse a StringBuilder. Imagine the following scenario:

StringBuilder sb = new StringBuilder();
foreach(var whatever in whateverlist)
{
  sb.Append("{0}", whatever);
}

//Perform some stuff with sb

//Clear stringbuilder here

//Populate stringbuilder again to perform more actions
foreach(var whatever2 in whateverlist2)
{
  sb.Append("{0}", whatever2);
}

And when clearing StringBuilder I can think of two possibilities:

sb = new StringBuilder();

or

sb.Length = 0;

What is the best way to clear it and why?

Thank you.

EDIT: I ment with current .NET 3.5 version.

11 Answers

C# In A Nutshell To clear the contents of a StringBuilder, there are two ways:

  1. Set its Length to zero:

    Setting a StringBuilder’s Length to zero doesn’t shrink its internal capacity. So, if the StringBuilder previously contained one million characters, it will continue to occupy around 2 MB of memory after zeroing its Length.

  2. Instantiate a new one:

    If you want to release the memory, you must create a new StringBuilder and allow the old one to drop out of scope (and be garbage collected), with this approach you can solve the previous item problem.

// P.S. to be ultra efficient 
// make a good guess at the initial allocation too !!!!
int PerWhatever_SizeEstimate = 4; // a guess of average length... you known your data
StringBuilder sb = new StringBuilder( whateverlist.Length * PerWhatever_SizeEstimate);

// reallocation needed? 
// if you want to be efficient speed and memory wise... 
sb.Length = 0;  // rest internal index but don't release/resize memory
// if a ...BIG... difference in size
if( whatever2.Length < whatever.Length * 2/3  
 || whatever2.Length > whatever.Length * 1.5)
{
    //scale capacity appropriately
    sb.Capaciy = sb.Capacity * whatever2.Length / whatever.Length;
}
Related