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.
Update It turns out that you are using .net 3.5 and
Clearwas added in .net 4. So you should useLength = 0. Actually I’d probably add an extension method namedClearto do this since it is far more readable, in my view, thanLength = 0.I would use none of those and instead call
Clear.I can’t imagine that it’s slower than any of your variants and I also can’t imagine that clearing a
StringBuilderinstance 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.