Using BenchmarkDotNet's memory diagnoser, this code seems to allocate 12B even when called with parameters
= null
:
public static void Usage(this ILogger logger, LogLevel logLevel, string area, string operation, Dictionary<string, string> parameters)
{
Func<Dictionary<string, string>> function = null;
if (parameters != null)
{
function = new Func<Dictionary<string, string>>(() =>
{
return parameters;
});
}
logger.Usage(logLevel, area, operation, function);
}
If I remove the assignment to function
, the allocation drops to 0. When I look at the IL code I can see the following lines:
IL_0000: newobj instance void MIT.Logging.Infrastructure.LoggerExtensions/'<>c__DisplayClass0_0'::.ctor()
IL_001f: newobj instance void class [mscorlib]System.Func`1<class [mscorlib]System.Collections.Generic.Dictionary`2<string, string>>::.ctor(object, native int)
The second line makes sense, it suppose to be conditional and in my specific case, the condition is NOT met. But the first one I can't explain.
This is the benchmark method:
[Benchmark]
public void Log_WithInfra_ExtensionMethodDirect_NoParameters()
{
LoggerExtensions.Usage(_logger, LogLevel.Information, LogAreas.MainApplication.AreaName, LogAreas.MainApplication.Operations.Operation0, null);
}
This is the benchmark results:
Method | Mean | Error | StdDev | Gen 0 | Allocated |
---|---|---|---|---|---|
Log_WithInfra_ExtensionMethodDirect_NoParameters | 8.441 ns | 18.732 ns | 1.027 ns | 0.0023 | 12 B |
It is stupid, it is not that important to my use case, but it drives me crazy.