Skip to content

Instantly share code, notes, and snippets.

@joncloud
Created August 10, 2017 03:11
Show Gist options
  • Select an option

  • Save joncloud/1e396b2542c0c49ea95a9b4936fe16b6 to your computer and use it in GitHub Desktop.

Select an option

Save joncloud/1e396b2542c0c49ea95a9b4936fe16b6 to your computer and use it in GitHub Desktop.
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
using System.Threading.Tasks;
namespace ConsoleApp5
{
class Program
{
static void Main(string[] args)
{
BenchmarkRunner.Run<LoggingBenchmark>();
}
}
[MemoryDiagnoser]
public class LoggingBenchmark
{
ILoggerFactory _factory;
IServiceProvider _serviceProvider;
[GlobalSetup]
public void Setup()
{
_serviceProvider = new ServiceCollection()
.AddLogging()
.BuildServiceProvider();
_factory = _serviceProvider.GetRequiredService<ILoggerFactory>();
}
[Benchmark]
public ILogger<LoggingBenchmark> OneFromFactory() => _factory.CreateLogger<LoggingBenchmark>();
[Benchmark]
public ILogger<LoggingBenchmark> OneFromServiceProvider() => _serviceProvider.GetRequiredService<ILogger<LoggingBenchmark>>();
[Benchmark]
public ILogger<LoggingBenchmark>[] ManyFromFactory()
{
var loggers = new ILogger<LoggingBenchmark>[10];
Parallel.For(0, loggers.Length, id => loggers[id] = _factory.CreateLogger<LoggingBenchmark>());
return loggers;
}
[Benchmark]
public ILogger<LoggingBenchmark>[] ManyFromServiceProvider()
{
var loggers = new ILogger<LoggingBenchmark>[10];
Parallel.For(0, loggers.Length, id => loggers[id] = _serviceProvider.GetRequiredService<ILogger<LoggingBenchmark>>());
return loggers;
}
}
}
BenchmarkDotNet=v0.10.9, OS=Windows 10 Redstone 2 (10.0.15063)
Processor=Intel Core i5-4258U CPU 2.40GHz (Haswell), ProcessorCount=4
Frequency=2343749 Hz, Resolution=426.6668 ns, Timer=TSC
.NET Core SDK=2.0.0-preview2-006497
  [Host]     : .NET Core 1.1.2 (Framework 4.6.25211.01), 64bit RyuJIT
  DefaultJob : .NET Core 1.1.2 (Framework 4.6.25211.01), 64bit RyuJIT

Method Mean Error StdDev Gen 0 Gen 1 Allocated
OneFromFactory 236.8 ns 6.258 ns 6.147 ns 0.0153 - 24 B
OneFromServiceProvider 190.3 ns 1.569 ns 1.391 ns - - 0 B
ManyFromFactory 8,806.5 ns 30.477 ns 28.508 ns 1.3702 0.0153 1626 B
ManyFromServiceProvider 8,090.3 ns 54.212 ns 50.710 ns 1.1902 0.0153 1478 B
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment