Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to clear contents of .NET's StringBuilder

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.

like image 463
David Espart Avatar asked Nov 10 '09 16:11

David Espart


People also ask

How do you clear the value of a StringBuilder?

Using setLength() method A simple solution to clear a StringBuilder / StringBuffer in Java is calling the setLength(0) method on its instance, which causes its length to change to 0. The setLength() method fills the array used for character storage with zeros and sets the count of characters used to the given length.

How do I remove all elements from string builder?

Clear Method is used to remove all the characters from the current StringBuilder instance.

How check StringBuilder is empty or not in C#?

Check if StringBuilder Is Empty Using the Length Property The StringBuilder class has a property named Length that shows how many Char objects it holds. If Length is zero that means the instance contains no characters.


1 Answers

If you're doing this in .NET 2.0 or 3.5, write an extension method to do it like this:

/// <summary> ///     Clears the contents of the string builder. /// </summary> /// <param name="value"> ///     The <see cref="StringBuilder"/> to clear. /// </param> public static void Clear(this StringBuilder value) {     value.Length = 0;     value.Capacity = 0; } 

Then, you can clear it like this:

someStringBuilder.Clear(); 

Then, when 4.0 comes out, you can ditch your extension method in favor of the 4.0 version.

UPDATE: It's probably not a good idea to set Capacity to zero. That will guarantee reallocations when you append to the builder, if you're reusing the same instance. However, the memory in the instance of the builder is not released until you set the Capacity to a very small value (such as 1). The default value of the Capacity property is 16. You might want to consider using 16, or (though it's less efficient) setting the capacity twice:

  • Set it to 1 or zero to clear the memory
  • Set it to your original Capacity value (which may differ from 16) to restore it.
like image 58
Mike Hofer Avatar answered Sep 28 '22 23:09

Mike Hofer