Two new features are introduced in C# 10.0 to improve interpolated strings C# 6.0, they are the new [InterpolatedStringHandler]
attribute and the DefaultInterpolatedStringHandler struct. Together these provide for improved default performance as well as the ability to create custom interpolated string handlers.
In prior versions of .NET most string interpolation expressions used String.Format
which is inefficient due to its flexibility, as well as boxing of value types and the creation of intermediate strings. This was especially problematic when used in loops or other performance-critical code and inefficient with logging where the log message is often discarded after all overhead is incurred.
By default the new DefaultInterpolatedStringHandler
will perform operations more akin to StringBuilder
but also allows for receivers to indicate that they can handle the interpolated string directly. This is done by applying the [InterpolatedStringHandler]
attribute to a method that takes the interpolated string as a parameter.
Additionally developers can create their own behavior to perform operations such as encoding values or better defer formatting until the string is actually needed.
Code
// Although log.LogInformation should be a no op if logging is disabled formatting is still performed
if (log.IsEnabled(LogLevel.Information))
{
log.LogInformation($"POST payload \"{json}\" parsed in {time}ms");
}
// Don't worry about the cost of formatting the string, the logger is using a interpolated string handler
log.LogInformation($"POST payload \"{json}\" parsed in {time}ms");