Skip to content

Instantly share code, notes, and snippets.

@usausa
Created July 25, 2020 13:42
Show Gist options
  • Save usausa/4ae8d81c2485245b34b3dea385fa03ee to your computer and use it in GitHub Desktop.
Save usausa/4ae8d81c2485245b34b3dea385fa03ee to your computer and use it in GitHub Desktop.
using System;
using System.Linq.Expressions;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Configs;
using BenchmarkDotNet.Diagnosers;
using BenchmarkDotNet.Exporters;
using BenchmarkDotNet.Jobs;
using BenchmarkDotNet.Running;
public static class Program
{
public static void Main(string[] args)
{
BenchmarkRunner.Run<Benchmark>();
}
}
public class BenchmarkConfig : ManualConfig
{
public BenchmarkConfig()
{
AddExporter(MarkdownExporter.Default, MarkdownExporter.GitHub);
AddDiagnoser(MemoryDiagnoser.Default);
AddJob(Job.LongRun);
}
}
public class Data
{
public string Value { get; set; }
}
[Config(typeof(BenchmarkConfig))]
public class Benchmark
{
private readonly Data data = new Data();
private Func<Data, string> getter1;
private Func<Data, string> getter2;
[GlobalSetup]
public void Setup()
{
getter1 = x => x.Value;
getter2 = ToFunc<Data, string>(x => x.Value);
}
private static Func<T, TRet> ToFunc<T, TRet>(Expression<Func<T, TRet>> expression)
{
return expression.Compile();
}
[Benchmark]
public string Getter1() => getter1(data);
[Benchmark]
public string Getter2() => getter2(data);
}
Method Mean Error StdDev Median Gen 0 Gen 1 Gen 2 Allocated
Getter1 1.2362 ns 0.0549 ns 0.2771 ns 1.3100 ns - - - -
Getter2 0.8595 ns 0.0372 ns 0.1903 ns 0.9295 ns - - - -
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment