-
Notifications
You must be signed in to change notification settings - Fork 4.2k
Description
String interpolation simplicity and clearness makes it very attractive for formatting text.
In fact, at my company I've seen it used for things as trivial as var greeting = $"Hello {name}", which admittedly is only slightly nicer than "Hello " + name.
The thing is: it doesn't have the same performance characteristics. Currently C# converts an interpolated string into a string.Format("Hello {0}", name) call. This has the benefit of being the simplest implementation (from a compiler perspective). But it has quite some overhead: boxing of value type placeholders (such as numbers), parsing of the format string, validation of the parameters, etc.
Most of the time you may not care. But sometimes in hot path code you want to be very careful with those allocations and computations.
I suggest that the compiler could generate more optimized code in at least some (or all?) situations.
It is evident that when you convert to FormattableString or IFormattable you'd need to generate a specialized class for each template, which may be excessive (or not?).
In the common case of interpolating strings, you could turn the parameters into strings at interpolation site, with specialized code, so that value types don't require boxing.
Concatenation of the results could be done with string.Concat, which doesn't require allocating an array for up to 4 parts.
This means that code like string s = $"x: {x}, y: {y}", which is a common use of string interpolation, could generate the IL equivalent of string s = string.Concat("x: ", x.ToString(), ", y: ", y.ToString()) which is probably the most efficient code you could have to create that string.
If the compiler did that work, we would get both benefits of clean syntax and most efficient specialized code.