3

Q :

Which one is performance wise : to clear a string builder

AStringBuilder.Remove(0,AStringBuilder.Length);

string theString = AStringBuilder.ToString();
ABuilder.Replace(theString,String.Empty);

AStringBuilder.Length = 0;

Note : I use Framework 3.5 which doesn't contain Clear() method.

Daniel Mann
  • 57,011
  • 13
  • 100
  • 120
Anyname Donotcare
  • 11,113
  • 66
  • 219
  • 392

3 Answers3

7

Update It turns out that you are using .net 3.5 and Clear was added in .net 4. So you should use Length = 0. Actually I'd probably add an extension method named Clear to do this since it is far more readable, in my view, than Length = 0.


I would use none of those and instead call Clear.

Clear is a convenience method that is equivalent to setting the Length property of the current instance to 0 (zero).

I can't imagine that it's slower than any of your variants and I also can't imagine that clearing a StringBuilder instance could ever be a bottleneck. If there is a bottleneck anywhere it will be in the appending code.

If performance of clearing the object really is a bottleneck then you will need to time your code to know which variant is faster. There's never a real substitute for benchmarking when considering performance.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
  • 1
    @just_name Use `Length = 0`. That's all that `Clear` is doing anyway. – vcsjones Jan 23 '12 at 15:41
  • It is correct to set Length=0 to empty a StringBuilder but keeping its memory. But when using StringBuilder.Insert(), this will not work. The Insert() will add more memory to the Stringbuilder, even if there is plenty of free memory in the StringBuilder already. If the StringBuilder is repeatedly inserted and cleared (i.e. Length=0), one gets an Out Of Memory exception finally. See my post: http://stackoverflow.com/questions/29574469/memory-leak-in-stringbuilder-when-using-insert-and-clear – Peter Huber Apr 13 '15 at 02:37
1

Before .NET 4: As David Heffernan mentions, use Length = 0;

In .NET 4: Other option: StringBuilder.Clear();

http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.clear.aspx

Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
RvdK
  • 19,580
  • 4
  • 64
  • 107
1

Since Clear() is not available for you, I think setting the Length to Zero is faster. Here are some benchmarks.

One more link from SO on StringBuilder performance.

Marcos Dimitrio
  • 6,651
  • 5
  • 38
  • 62
V4Vendetta
  • 37,194
  • 9
  • 78
  • 82