Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

which string operation is better? [duplicate]

Tags:

c#

.net

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");
like image 996
5YrsLaterDBA Avatar asked Jul 20 '10 19:07

5YrsLaterDBA


1 Answers

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:

msgEntry.AppendFormat("<{0}>{1}</{0}>", timeTag, timeStamp);

You haven't shown what you want to do with the StringBuilder afterwards. If you're just going to convert it to a string, then I'd use:

string text = string.Format("<{0}>{1}</{0}>", timeTag, timeStamp);

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:

  • Make sure your architecture is reasonably efficient - that's hard to change later.
  • Balance your internal design between efficiency and simplicity, with an emphasis on testability; changing the design later may take a while, but it should usually be feasible without compatibility issues.
  • Write your implementation to be as readable as possible.
  • Measure the system to find out whether it performs well enough, and where the bottlenecks are. They're almost never going to be in code like this. (We're not talking about string concatenation in a loop here, after all.)
  • When you've found a bottleneck, try different optimizations and measure them too. Don't assume that something you think will be faster will actually be faster.

1 Or the array to pass to Concat... we don't know the type of timeStamp so 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.

like image 74
Jon Skeet Avatar answered Sep 22 '22 14:09

Jon Skeet