Skip to content

String interpolation can be optimized #22594

@KrisVandermotten

Description

@KrisVandermotten

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:

  1. The interpolated string has no fill-ins. This case is handled already.
  2. None of the fill-ins have alignment or format specifiers, and they are all strings.
  3. 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).
  4. None of the fill-ins have alignment or format specifiers, and some of them are value types.
  5. 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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions