Consider this code:
var url = "www.example.com";
String.Format:
var targetUrl = string.Format("URL: {0}", url);
String Interpolation:
var targetUrl=$"URL: {url}";
Which of one from string interpolation and string.Format
is better in performance?
Also what are the best fit scenarios for use of them?
Under most conditions they're the same, but not if you're using them in a logging statement.
If you use the {0} format the argument won't get translated into a string until after the logging framework has decided whether or not to emit this message.
Hence, in a log.Debug() call where you're only outputting Info and above, the {myVar} format always pays the binary to text tax, whereas the {0} format only pays the tax when you actually want it.
In the case of passing a string it doesn't matter, but for binary data and floating point data it can make quite a difference.
Neither of them is better since they are equal on run-time. String interpolation is rewritten by the compiler to
string.Format
, so both statements are exactly the same on run-time.Use string interpolation if you have variables in scope which you want to use in your string formatting. String interpolation is safer since it has compile time checks on the validness of your string. Use
string.Format
if you load the text from an external source, like a resource file or database.