Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 974
Ahmed Inam Avatar asked Jun 23 '16 07:06

Ahmed Inam


People also ask

Is string format faster than interpolation?

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.

Why do we use string interpolation?

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.

Which character should be used for string interpolation?

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.

Is string format faster than concatenation C#?

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.


Video Answer


1 Answers

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.

like image 135
Patrick Hofman Avatar answered Oct 11 '22 12:10

Patrick Hofman