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?
The InterpolateExplicit() method is faster since we now explicitly tell the compiler to use a string . No need to box the object to be formatted.
The string interpolation feature is built on top of the composite formatting feature and provides a more readable and convenient syntax to include formatted expression results in a result string. Interpolated strings support all the capabilities of the string composite formatting feature.
To identify a string literal as an interpolated string, prepend it with the $ symbol. You can't have any white space between the $ and the " that starts a string literal.
I have taken a look at String. Format (using Reflector) and it actually creates a StringBuilder then calls AppendFormat on it. So it is quicker than concat for multiple stirngs.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With