Benchmarks of the logging with LoggerMessage
Recently, I came across the following site: High-performance logging with LoggerMessage in ASP.NET Core.
It says that the logging using LoggerMessage.Define style is a high-performance logging pattern because of:
- boxing of arguments when using extension methods
- repetitive message template parsing
Fair enough, so I decided to do a benchmark comparing LoggerMessage vs Logger extension method vs. string.Format logging.
I decided to do it because after checking the code:
boxing of the value types in LoggerMessage.Define style is happening anyway , just later, inside the class LogValues<Tx> (see the method ToArray ).
The same is for the message template parsing (see Microsoft.Extensions.Logging.Internal.LogValuesFormatter.Format method).
The benchmark sample
In the sample for the benchmark I setup logging infrastructure without actually writing the messages anywhere. I wanted to measure just the overhead of the different logging style.
The results are:
As you can see, LoggerMessage style of logging is really faster then logging via extension methods but the difference is really small and the code change is quite significant. I saw a discussion that the team wanted to migrate the code base to LoggerMessage style because it's high performant logging. I wouldn't invest in it for already running project.
At the end of the day, LoggerMessage looks promising, especially if the parsing the message template without boxing would be really implemented. I thought the LoggerMessage.Define parses the message template and generate a custom method on the fly for creating the result message.
What do you think?