The safest and most efficient way to clear a StringBuilder variable is as follows
stringBuilder sbr = new StringBuilder(); // loop // more code // clear sbr variable sbr.Length = 0;
Why ?
It is a well know fact in the .Net community that using StringBuilder for string concatenation and manipulation is far more efficient that using the string class. The problem arises when you need to clear the StringBuilder variable. For regular string variables, you would simply set the variable equal to “”. However, you cannot do that with the StringBuilder class. Moreover, the StringBuilder does not have a Clear() method as one would expect.
So when using a StringBuilder in a loop, for example, to read from a DataReader and write to a FileStream line by line, you are left with atleast 3 choices.
Using the Remove() method is not efficient, and could also throw an error if your variable has no characters in it. Using new to recreate the instance is obviously a performance overhead. So Of these 3, I would recommend that the last option.
Using the Clear() method is the safest and most efficient !
I am confused – in the first part of the post, you mentioned that the StringBuilder class does not have a Clear() method (which is does not), but then you end the post with the statement that using the Clear() method is the safeest and most efficient.
Which is it? Is it really setting the length to 0 that is the most efficient (and safest)?