The second is probably a little better in terms of memory usage, because it does not need to calculate intermediate line 1 ... but it is less readable, IMO.
Personally, I would use:
msgEntry.AppendFormat("<{0}>{1}</{0}>", timeTag, timeStamp);
After that, you did not show what you want to do with StringBuilder . If you are going to convert it to a string, I would use:
string text = string.Format("<{0}>{1}</{0}>", timeTag, timeStamp);
to start.
What is the performance? Well, probably worse - in the end, he had to parse the format string. But didn’t you measure it and find that it is a bottleneck, why are you worried?
Generally:
- Make sure your architecture is efficient enough - it's hard to change later.
- The balance of your interior design between efficiency and simplicity, with an emphasis on testability; changing the design later may take some time, but it should be practicable without compatibility issues.
- Write your implementation as readable as possible.
- Measure the system to find out if it works enough and where the bottlenecks are. They almost never will be in such code. (After all, we are not talking about string concatenation in a loop.)
- When you find a bottleneck, try various optimizations and evaluate them. Do not assume that what you think will be faster will actually be faster.
1 Or an array to go to Concat ... we don’t know the type of timeStamp , so we can’t say exactly what happens there; in the second form, it can be added in place, while the first form may need to be inserted and then converted to a string before performing concatenation.
Exact implementation for redistribution, etc. may change between .NET 3.5 and .NET 4 (I know some implementation bits have). Without a very thorough benchmarking, I would be very sorry to say that it is faster ... but readability is easier to name, although subjectively.
Jon skeet
source share