-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)} )";
4
  • 3
    Have you benchmarked them? Commented Feb 25, 2016 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.". Commented Feb 25, 2016 at 10:33
  • You should check out what StackOverflow's own Nick Craver was tweeting about last night (link to first of a few tweets discussing this). Commented Feb 25, 2016 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?" Commented Feb 25, 2016 at 15:31

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

1 Comment

Link-only answers aren't answers. Include the relevant details from the link into your answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.