You just don't get any good value just "asking" about these kinds of things. You need to benchmark. Take this code for example:
var sw = Stopwatch.StartNew();
var cc0 = GC.CollectionCount(0);
var s = (string)null;
for (var i = 0; i < 10000000; i++)
{
s = "a";
s += "b";
}
var cc1 = GC.CollectionCount(0);
sw.Stop();
Console.WriteLine(
"collections == {0}, ms == {1}, string == \"{2}\"",
cc1 - cc0,
sw.ElapsedMilliseconds,
s);
Versus this code:
var sw = Stopwatch.StartNew();
var cc0 = GC.CollectionCount(0);
var sb = (StringBuilder)null;
for (var i = 0; i < 10000000; i++)
{
sb = new StringBuilder();
sb.Append("a");
sb.Append("b");
}
var cc1 = GC.CollectionCount(0);
Console.WriteLine(
"collections == {0}, ms == {1}, string == \"{2}\"",
cc1 - cc0,
sw.ElapsedMilliseconds,
sb.ToString());
The two results I get are:
collections == 63, ms == 336, string == "ab" // +=
collections == 228, ms == 692, string == "ab" // StringBuilder
The StringBuilder
takes over twice as long and causes over 3.5 times more garbage collections to occur.
It's certainly the case that if I were to concatenate very long strings that StringBuilder
will perform better, but I won't know that point unless I measure it.
You need to provide more detail as to what code you are running and what you mean by "better" (faster, less memory, easy to read code, etc) before we can say what is best.