0

I'm making a automatic download program. I used to use String.Format() when I have to combine two or three strings, and suddenly I'm curious about the efficiency of String.Format().

Let me explain. When I combine address and some parameters for targetting URL, I'll use the function like this:

string.Format("http://example.com/{0}?foo=bar", foo);

and display progress information to user, the implementation will be like this:

string.Format("{0}/{1}", foo_current, foo_all);

What I want to know is string.Format() is always more efficient than "+" operator when combining multiple strings.

I learned combining strings with + operator can make a lot of overheads. then, What should I do for combining strings efficiently?

Kangjun Heo
  • 1,023
  • 1
  • 8
  • 19
  • I just leave [it](http://stackoverflow.com/a/18342/1849444) here. – teo van kot Mar 01 '17 at 05:50
  • “What I want to know is string.Format() is always more efficient than "+" operator when combining multiple strings.” It pretty much never is, but it can be more readable sometimes. – Ry- Mar 01 '17 at 05:51
  • You should know one big difference, string.Format uses StringBuilder for effective memory allocation and when use `string a = x + y + z + etc ` for every plus there are new memory allocation and with `string a = string.Format("{0}{1}{2}{3}", x, y, z, etc)` you will have one allocation for string and one for string builder. – Alex Pashkin Mar 01 '17 at 06:00
  • 1
    More readable is use new syntax `$"http://example.com/{bar}?foo=bar"` – Alex Pashkin Mar 01 '17 at 06:01
  • @Sentry: No? The very first answer has 618 ms for `String.Format` and 166 ms for `+`. The third answer uses `Console.WriteLine`, not `String.Format`, and obviously did the benchmark completely wrong (“the very first operation is ALWAYS much slower”). Fourth answer again has `+` being faster than `String.Format`. – Ry- Mar 01 '17 at 06:15
  • @AlexPashkin Repeated inline `+` tends to be optimized by the compiler and doesn’t allocate for each concatenation. (`+=` in a loop is another story.) – Ry- Mar 01 '17 at 06:18
  • Building urls with String.Format generally produces invalid urls, so to some extent performance of such operations do not matter as you can replace them with any other invalid code or remove that code altogether. – Alexei Levenkov Mar 01 '17 at 07:00
  • @Ryan: I have no excuse, probably not enough sleep. I checked it three times and still mixed it up, sorry. I'll delete my comment tomorrow, it adds nothing of value and is only embarrassing – Sentry Mar 01 '17 at 13:27

0 Answers0