String Interpolation under the hood in C#
In this article, we will discuss how string interpolation works under the hood and how InterpolatedStringHandler solves many memory issues of string interpolation. let’s see string interpolation work before C# 10
We notice that string interpolation is converted to a string. Format the problem here is boxing all value types will be added in a heap instead of a stack and this will pressure for GC(Garbage collection).
but if we upgrade our project to dotnet 6 c# 10
we notice that no boxing happens the age and number are int and not converted to an object this is a big performance and memory effective in real projects we have a lot of message interpolation
but what is the problem with this approach in some cases it is not more effective let’s see our example, We have the ValidateAge method that take a message when age is not valid
let’s see our low-level code
The problem here is that append message in the interpolatedStringHandler and add allocate in memory before checking that age is valid for the benchmark result
To solve this problem we can make a custom InterpolatedStringHandler can use in a lot of methods
low-level code check that the condition is true first and then appends, note that the AppendLiteral method adds pure string and the AppendFormatted method is a generic method so there is no boxing needed. There are a lot of examples like logging in logging you need to check that the log level is enabled before adding a string and a lot of that need customer interpolated
you can read about string handlers by logging in to this article string handler Code.