2

Is there any difference between writing the following two? The code is for C#

String S1 = "The " + Item.Name + " is made of " + Item.Property + " and is at " + Item.Durability + "% durability."

against

String S2 = "The {0} is made of {1} and is at {2} % durability.", Item.Name, Item.Property, Item.Durability

? Assuming that item is populated with, for instance, name of Axe, property of Steel, and durability of 50 as a string.

Charles
  • 548
  • 1
  • 7
  • 25

3 Answers3

2

The second one is faster, assuming you correctly use it with String.Format.

In the first approach, you're internally forcing the system to sequentially build an incrementally larger string, triggering at least a full allocation and internal copy for each of the + operations.

In the second, you're letting internally optimized functions first assess all of the parameters, and allocate a single string to contain the entire end result in one go, and copy it in.

Niels Keurentjes
  • 41,402
  • 9
  • 98
  • 136
  • 1
    No, it should be optimized to `String.Concat`. – Ry- Jul 07 '14 at 21:41
  • Thanks for the input both of you. I'd been using + and += for a while now, and I knew += created a new string instance but not that "A " + b + " C " + d would create new instances on each +. I'll look up concat and try to switch my style to {0}, with string.format (which I did not know was required/recommended for all {0} operations.) – Charles Jul 07 '14 at 22:23
  • @Charles: It doesn’t create a new instance on each `+`. Multiple concatenation like that (not in a loop) is optimized to `String.Concat`. Multiple concatenation in a loop should be done with `StringBuilder`. – Ry- Jul 07 '14 at 22:36
  • @false correct, but that's assuming compiler smartness. I don't think it's in the spec that the compiler should do that. Relatively moot point of course given that MS writes the only serious compiler, but still :) – Niels Keurentjes Jul 08 '14 at 07:54
1

Yes, the second one give to you a single string, for your code is worng, you have to use string.Format method, so it is has a better performance than first one.

String S2 = string.Format("The {0} is made of {1} and is at {2} % durability.", Item.Name, Item.Property, Item.Durability);

The first one will generate a lot of strings and do the concatenation operation between + operator.

If you have a concatenation inside a loop, the recomentation is to use StringBuilder class.

Take a look at this post: Most efficient way to concatenate strings?

Community
  • 1
  • 1
Felipe Oriani
  • 37,948
  • 19
  • 131
  • 194
1

Assuming you correct your second example to use String.Format, they should produce the exact same result, yes.

I personally prefer using String.Format because it gives me more control. Also, I've always assumed it might be more efficient, although I've done no testing to verify that.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466