String.Format() VS operator "+" VS StringBuilder
2010-Лют-03, Середа 16:07| Method | Ticks |
|---|---|
| String.Format | 4,062,500 |
| String Concatenation | 2,781,250 |
| StringBuilder | 3,531,250 |
Original.
The straight answer to this, is, it depends. If you do a search on the web for benchmark comparisons between string.Format(), vanilla string concatenation, and StringBuilder.Append() you'll see that each of those calls are better suited for different circumstances.
It's best to avoid string.Format() (which internally calls StringBuilder.AppendFormat()) unless you are actually trying to apply some formatting to a string (eg formatting a numeric representation to 2 decimal places).
So if you have no requirements in sight for that scenario, it leaves you with string concatenation and StringBuilder as options. It turns out that vanilla string concatenation is faster for small sets of concatenation. When you start going into situations where you are concatenating a large number of strings, StringBuilder.Append() clearly wins out.
Another thing to consider is that in .NET strings are immutable. This means that when you do this:
string x = "123";
x = x + "456"
x = "something else";
three strings are created in memory ("123", "123456" and "something else").
x will remain assigned to "something else" while the other two strings ("123" and "123456") will remain in memory until the garbage collector fires up to mark and sweep them. One of the main reasons to use StringBuilder.Append() is to avoid this.
The moral here is to benchmark your app in terms of both performance and memory usage. Even if you are getting good performance by relying on vanilla string concatenation, you may be enlarging your memory footprint. Garbage collection will occur when Generation 0 reaches capacity. Thus this may also encourage the GC to start earlier than it might otherwise, which itself is an expensive operation.
Here's a link with some benchmarks that may help you decide:
http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm