Which one is performance wise : to clear a string builder
string theString = AStringBuilder.ToString(); ABuilder.Replace(theString,String.Empty);
AStringBuilder.Length = 0;
Note : I use Framework 3.5 which doesn’t contain
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
Clearis 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.
Answered By – David Heffernan
Answer Checked By – Marie Seifert (BugsFixing Admin)