I would like to ask what you think is the best way (lasts less / consumes less resources) to clear the contents in order to reuse a StringBuilder. Imagine the following scenario:
StringBuilder sb = new StringBuilder();
foreach(var whatever in whateverlist)
{
sb.Append("{0}", whatever);
}
//Perform some stuff with sb
//Clear stringbuilder here
//Populate stringbuilder again to perform more actions
foreach(var whatever2 in whateverlist2)
{
sb.Append("{0}", whatever2);
}
And when clearing StringBuilder I can think of two possibilities:
sb = new StringBuilder();
or
sb.Length = 0;
What is the best way to clear it and why?
Thank you.
EDIT: I ment with current .NET 3.5 version.
Length
is writable, but there isn't a read/write "Text" property? Sayingsb.Text = "";
would seem clearer thatsb.Length = 0;
, and aText
property would also help in the common scenario where one would otherwise have to saysb.Length = 0; sb.Append(StuffToStartWith);
. – Levins.Text
property encourages people to accidentially writesb.Text = sb.Text + nextString;
, defeating the whole point of using aStringBuilder
in the first place. – FormylSet
method rather than a property, but if one took such an approach I see no reasonLength
shouldn't be treated suitably, especially since there would be uses for different ways of handling lengthening and shortening scenarios. – Levins