-3

Of these two methods of string interpolation (string.Format and the "$" operator), is one better than the other and if so, in what situations and why?

Examples of both doing the same thing:

//string.Format
string s = string.Format("( {0} ) , ( {1} )", string.Join(", ", columnNames),string.Join(", ",values));

//"$" interpolation operator
string s = $"( {string.Join(", ", columnNames)} ) , ( {string.Join(", ", values)} )";
Alfie Goodacre
  • 2,753
  • 1
  • 13
  • 26
  • 3
    Have you benchmarked them? – ChrisF Feb 25 '16 at 10:31
  • 3
    Stack Overflow users are kind of biased against premature optimization, and rightfully so. In general, stuff like this really doesn't matter unless you want to execute it hundreds of thousands of times, while your code is not doing anything else. As soon as disk or network access comes into play, the relatively tiny performance differences, if any, won't matter at all in the bigger picture. See also the classical ["If you have two horses and you want to know which of the two is the faster then **race your horses**."](http://ericlippert.com/2012/12/17/performance-rant/). – CodeCaster Feb 25 '16 at 10:33
  • You should check out what StackOverflow's own Nick Craver [was tweeting about last night](https://twitter.com/Nick_Craver/status/702691498383511552) (link to first of a few tweets discussing this). – James Thorpe Feb 25 '16 at 10:42
  • Am I the only one who initially read the title to mean "is it quicker to *write code* using string.Format or interpolation?" and thinking to myself "is this a trick question?" – BoltClock Feb 25 '16 at 15:31

2 Answers2

2

String interpolation is turned into string.Format() at compile-time so they should end up with the same result. (link)

Community
  • 1
  • 1
M.REJEB
  • 76
  • 1
  • 5
0

Benchmark has been done, please check this out

Globally, it is similar to string.Format, but variables may be accessed directly (not through index arguments) so you won't notice any major difference.

But if you are looking for performance, the length of the strings to be concatenate will make the choice between the different concatenantion methods very difficult.

norisknofun
  • 859
  • 1
  • 8
  • 24