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

2

12

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

Airbrush answered 23/6, 2016 at 7:33 Comment(3)
Do you faced with the case, when lines from above are slow?Pheidippides
I found string interpolation slightly slower than string.format in my code as well as in this link.Airbrush
The linked post shows almost identical results for string.Format and string interpolation (which is true). This looks like premature optimization issue.Pheidippides
L
20

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.

League answered 23/6, 2016 at 7:35 Comment(1)
This is no longer correct - Since c#10 / .Net-6 Interpolation is only rewritten by the compiler to string.Format as a fallback when it doesn't find a better way. There are optimisations for various instances. See devblogs.microsoft.com/dotnet/…Gavelkind
D
4

Under most conditions they're the same, but not if you're using them in a logging statement that accepts a format string. (ex: log.Debug("URL: {0}", url))

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, whereas the {myVar} format is translated to a string before the function is entered.

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.

Duma answered 22/3, 2018 at 17:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.