Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which one is performance wise to clear a string builder?

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.

like image 256
Anyname Donotcare Avatar asked Dec 31 '25 16:12

Anyname Donotcare


1 Answers

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.

like image 133
David Heffernan Avatar answered Jan 02 '26 05:01

David Heffernan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!