Possible Duplicate:
String concatenation vs String Builder. Performance
Any difference (performance and memory usage) between the following two options?
option 1:
StringBuilder msgEntry = new StringBuilder();
msgEntry.AppendLine("<" + timeTag + ">" + timeStamp + "</" + timeTag + ">");
options 2:
StringBuilder msgEntry = new StringBuilder();
msgEntry.Append("<");
msgEntry.Append(timeTag);
msgEntry.Append(">");
msgEntry.Append(timeStamp);
msgEntry.Append("</");
msgEntry.Append(timeTag );
msgEntry.Append(">\n");
The second is possibly slightly better in terms of memory use, because it doesn’t need to compute the intermediate string1… but it’s less readable, IMO.
Personally I’d use:
You haven’t shown what you want to do with the
StringBuilderafterwards. If you’re just going to convert it to a string, then I’d use:to start with.
What’s the performance like? Well, probably worse – after all, it’s got to parse the format string. But unless you’ve measured this and found it to be the bottleneck, why are you worried?
In general:
1 Or the array to pass to
Concat… we don’t know the type oftimeStampso we can’t tell exactly what’s going on there; in the second form it may be appended in-place whereas the first form may need to box it and then convert it to a string before performing the concatenation.The exact implementation for reallocation etc may well have changed between .NET 3.5 and .NET 4 (I know some bits of the implementation have). Without very careful benchmarking, I’d be really loathe to say which is faster… but the readability is easier to call, albeit subjectively.