Use cached ILogger instances to avoid repeated creation of these instances#53200
Use cached ILogger instances to avoid repeated creation of these instances#53200adityamandaleeka merged 1 commit intodotnet:mainfrom
Conversation
|
Thanks for your PR, @gfoidl. Someone from the team will get assigned to your PR shortly and we'll get it reviewed. |
|
The generic method looks prettier! Can this issue be fixed in runtime? https://github.com/dotnet/runtime/blob/cd7e4cacce3b47a2560bc9ec746f0825a43f99d7/src/libraries/Microsoft.Extensions.Logging.Abstractions/src/LoggerFactoryExtensions.cs |
|
|
I don't suppose you have any numbers indicating how many instantiations this saves? The change looks unobjectionable and is probably acceptable as a speculative improvement, but my intuition is that it doesn't actually help that much in most cases. cc @captainsafia for MVC and @BrennanConroy for SignalR |
I can't tell you how many instantiations it saves, but I just did a quick comparison with NLog provider by creating 10,000,000 instances of
Of course that's a contrived example, but it shows that both performance and memory are being wasted when using generic |
|
I was curious what the perf difference would be, so I wrote a quick benchmark and ran it. The TL;DR is that it's ~20% better in time and memory to use Benchmarkusing BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Diagnosers;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
namespace DotNetBenchmarks;
[MemoryDiagnoser]
public class ILoggerFactoryBenchmarks
{
private static readonly ILoggerFactory Factory = NullLoggerFactory.Instance;
[Benchmark(Baseline = true)]
public ILogger CreateLogger_Generic()
{
return Factory.CreateLogger<MyClass>();
}
[Benchmark]
public ILogger CreateLogger_Type()
{
return Factory.CreateLogger(typeof(MyClass));
}
private sealed class MyClass
{
}
}
|
|
Change looks sensible. #50184 was the first PR to introduce this modification to the codebase. |
|
@captainsafia It would have been even better if |
|
/azp run |
|
Azure Pipelines successfully started running 3 pipeline(s). |
|
Thanks @gfoidl and sorry for the delay in review. |
|
/azp run |
|
Azure Pipelines successfully started running 3 pipeline(s). |
The basic "problem" is shown by this simple demo:
So for
loggerFactory.CreateLogger("foo")andloggerFactory.CreateLogger(typeof(Foo))cached instances ofILoggerare returned.For
loggerFactory.CreateLogger<Foo>()always a new instance ofILogger<Foo>is created.This PR basically does
where the
ILogger