Since .NET Framework[2.0 or 3.5] does not provide the “Clear” Method for StringBuilder class, sometimes as a developer you may come accross a sitution like using the StringBuilder object for concatenation operation of some sets of random number of string and then empty it and again re-use it for another concatenation operation. So there are various way to do this and following are some some options.
Option #1: Using Remove() Method
Example :
StringBuilder oStringBuilder = new StringBuilder(); oStringBuilder.Append("This is for testing"); oStringBuilder.Remove(0, oStringBuilder.Length); // Remove the characters from beginning. Option #2: Using Replace() Method
Example :
StringBuilder oStringBuilder = new StringBuilder(); oStringBuilder.Append("This is for testing"); string strStringBuilderContent = oStringBuilder.ToString(); oStringBuilder.Replace(strStringBuilderContent, string.Empty); // Replace with empty string.
Option #3: By Creating a new StringBuilder object
Example :
StringBuilder oStringBuilder = new StringBuilder(); oStringBuilder.Append("This is for testing"); oStringBuilder = new StringBuilder();
Option #4: Set the Length Property to zero
Example :
StringBuilder oStringBuilder = new StringBuilder(); oStringBuilder.Append("This is for testing"); oStringBuilder.Length = 0; // Set Length equal to zero
So here the question is which is the better way to follow and the answar is the Option #4 because :
# By setting length equal to zero it make the same StringBuilder object re-usable without modifying the buffer Capacity. # The .NET Framework 4.0 provides the “Clear” Method to StringBuilder class which is equivalent to this implementation. For more deatil please follow the link below :
http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.clear.aspx
# For comparison of perfomance, please follow the below link:
A short description about StringBuilder class:
# The StringBuilder object keeps a buffer which holds the new data appended to it.
# The default capacity of the buffer is 16k and it can be maximum up to Int32.MaxValue.
# The Capacity of the buffer can be changeable using the property “Capacity“.
# The StringBuilder object only allocates memory if the StringBuilder object buffer capacity is too small to holds the new data.
Concatenation operation [ String VS StringBuilder ]:
# String object concatenation operation always create a new object for each concatenation operation which indicates allocation of memory each time. # However, StringBuilder object maintains a buffer to accommodate new data, So it only allocates memory if the new data size exceed the buffer capacity.
# So concatenation using StringBuilder object for random number of strings, is having some perfomance advantage over using string object .
For more detail please follow the link below:
http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/