Search code examples
c#string-formattingc#-6.0string-interpolation

Which of one from string interpolation and string.format is better in performance?


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?

According to C# docs string interpolation so maybe there is no difference at all?

... it's typically transformed into a String.Format method call


Solution

  • Which of one from string interpolation and string.format is better in performance?

    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.

    Also what are the best fit scenarios for use of them?

    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.