I am little confused about using StringBuilder
class, first:
A
string
object concatenation operation always creates a new object from the existingstring
and the new data. AStringBuilder
object maintains a buffer to accommodate the concatenation of new data. New data is appended to the end of the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, then the new data is appended to the new buffer.
But where is the point of creating StringBuilder
instance to avoid creating new one of String
? It sounds like trading "one for one".
static void Main(string[] args)
{
String foo = "123";
using (StringBuilder sb = new StringBuilder(foo)) // also sb isn't disposable, so there will be error
{
sb.Append("456");
foo = sb.ToString();
}
Console.WriteLine(foo);
Console.ReadKey();
}
Why I shouldn't just use
+=
Edit: Ok, I know now how to reuse one instance of StringBuilder
(still don't know if this is right with code standards), but this isn't worth to use with just one string
, isn't it?