String interpolation has proven to be a very successful feature. Some people even replace efficient concatenation by interpolation, assuming the new syntax is just as efficient. However, that is not the case.
The LDM of May 21, 2014 noted:
The compiler would be free to not call String.Format, if it knows how to do things more optimally. This would typically be the case when there are no format specifiers in the string.
So far, nothing has been done to optimize interpolated strings in this way.
I believe there are five scenarios:
- The interpolated string has no fill-ins. This case is handled already.
- None of the fill-ins have alignment or format specifiers, and they are all strings.
- None of the fill-ins have alignment or format specifiers, and they are all of reference type, some of which are not string (and may or may not implement
IFormattable).
- None of the fill-ins have alignment or format specifiers, and some of them are value types.
- Some of the fill-ins have alignment or format specifiers.
Case 2 is surprisingly common. Last time I counted, Roslyn.sln had 1355 cases. It is also the easiest one to optimize. Basically, the call to string.Format can be replaced with string concatenation. That string concatenation is itself then lowered, often to a call to string.Concat. That lowering will perform constant folding, so in some cases no call is needed at all. Performance differences can be significant.
I have prepared pull request #22595 to handle this case.
String interpolation has proven to be a very successful feature. Some people even replace efficient concatenation by interpolation, assuming the new syntax is just as efficient. However, that is not the case.
The LDM of May 21, 2014 noted:
So far, nothing has been done to optimize interpolated strings in this way.
I believe there are five scenarios:
IFormattable).Case 2 is surprisingly common. Last time I counted, Roslyn.sln had 1355 cases. It is also the easiest one to optimize. Basically, the call to
string.Formatcan be replaced with string concatenation. That string concatenation is itself then lowered, often to a call tostring.Concat. That lowering will perform constant folding, so in some cases no call is needed at all. Performance differences can be significant.I have prepared pull request #22595 to handle this case.