Skip to content

Instantly share code, notes, and snippets.

@maryamariyan
Created March 26, 2021 07:27
Show Gist options
  • Save maryamariyan/8e441f9b86dc4d7b3cc85b54b873d235 to your computer and use it in GitHub Desktop.
Save maryamariyan/8e441f9b86dc4d7b3cc85b54b873d235 to your computer and use it in GitHub Desktop.
noop vs disable logging
public class Program
{
public static void Main()
{
var summary = BenchmarkRunner.Run<LogBenchmark>();
}
}
#pragma warning disable CA1822 // Mark members as static
#pragma warning disable LA0000 // Switch to updated logging methods using the [LoggerMessage] attribute for additional performance.
[MemoryDiagnoser]
public class LogBenchmark
{
private static Action<ILogger, string, long, long, int, Exception?> _loggerMessage2 = LoggerMessage.Define<string, long, long, int>(LogLevel.Debug,
eventId: 381,
formatString: @"Connection id '{connectionId}', range [{start}..{end}], options {options}");
private static ILogger _logger;
private const string ConnectionId = "0x345334534678";
private const long Start = 42;
private const long End = 123456789;
private const int Options = 0x1234;
private const int NumLoops = 1000;
[GlobalSetup]
public void GlobalSetup()
{
var serviceProvider = new ServiceCollection()
.AddLogging(logBuilder =>
{
//logBuilder.AddConsole().ClearProviders();
logBuilder.AddConsole().SetMinimumLevel(LogLevel.Information);
})
.BuildServiceProvider();
_logger = serviceProvider.GetRequiredService<ILoggerFactory>().CreateLogger<LogBenchmark>();
}
[Benchmark]
public void LogDebugNoop()
{
for (int i = 0; i < NumLoops; i++)
_logger.LogDebug(@"Connection id '{connectionId}', range [{start}..{end}], options {options}", ConnectionId, Start, End, Options);
}
[Benchmark]
public void LoggerMessageNoop()
{
for (int i = 0; i < NumLoops; i++)
_loggerMessage2(_logger, ConnectionId, Start, End, Options, null);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment