Skip to content

Instantly share code, notes, and snippets.

@eramax
Created June 15, 2021 18:45
Show Gist options
  • Save eramax/a74853fd28669bdd0d6ddeb6df82469d to your computer and use it in GitHub Desktop.
Save eramax/a74853fd28669bdd0d6ddeb6df82469d to your computer and use it in GitHub Desktop.
Reflection in C#
using BenchmarkDotNet.Running;
using BenchmarkDotNet.Attributes;
using System.Reflection;
using System;
using Sigil;
BenchmarkRunner.Run<MyTests>();
[MemoryDiagnoser]
public class MyTests
{
readonly MyTestableClass obj;
readonly PropertyInfo propertyInfo;
readonly Func<MyTestableClass, string> Delegate1;
readonly Func<MyTestableClass, string> CompiledDelegate1;
readonly Func<MyTestableClass, string> ILDelegate;
public MyTests()
{
obj = new MyTestableClass();
Delegate1 = x => x.PublicName;
propertyInfo = typeof(MyTestableClass).GetProperty("PrivateName", BindingFlags.Instance | BindingFlags.NonPublic);
MethodInfo method = propertyInfo.GetGetMethod(true);
CompiledDelegate1 = (Func<MyTestableClass, string>)Delegate.CreateDelegate(typeof(Func<MyTestableClass, string>), method);
ILDelegate = Emit<Func<MyTestableClass, string>>.NewDynamicMethod("Get").LoadArgument(0)
.CastClass(typeof(MyTestableClass)).Call(method).Return().CreateDelegate();
}
[Benchmark]
public string simpleGet() => obj.PublicName;
[Benchmark]
public string simpleDelegateGet() => Delegate1(obj);
[Benchmark]
public string RefactoringGet() => propertyInfo!.GetValue(obj)!.ToString();
[Benchmark]
public string CompiledDelegate() => CompiledDelegate1(obj);
[Benchmark]
public string EmitDelegate() => ILDelegate(obj);
}
public class MyTestableClass
{
private string PrivateName { get; set; } = "Private";
public string PublicName { get; set; } = "Public";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment