|
using System.Linq.Expressions; |
|
using System.Reflection; |
|
using BenchmarkDotNet.Attributes; |
|
using BenchmarkDotNet.Running; |
|
|
|
BenchmarkRunner.Run<ReflectionPerformance>(); |
|
|
|
public class ReflectionPerformance |
|
{ |
|
private static Person p = new() { Name = "bob" }; |
|
|
|
[Benchmark] |
|
public string RegualarProperty() |
|
{ |
|
return $"{p.Name}"; |
|
} |
|
|
|
[Benchmark] |
|
public string Reflection() |
|
{ |
|
var property = Person.GetPropertyInfo(); |
|
|
|
return $"{property.GetValue(p)}"; |
|
} |
|
|
|
private static readonly PropertyInfo cachedProperty = Person.GetPropertyInfo(); |
|
|
|
[Benchmark] |
|
public string CachedReflection() |
|
{ |
|
return $"{cachedProperty.GetValue(p)}"; |
|
} |
|
|
|
[Benchmark] |
|
public string Expression() |
|
{ |
|
var propertyGetter = Person.CreatePropertyGetterExpression(); |
|
|
|
return $"{propertyGetter(p)}"; |
|
} |
|
|
|
private static readonly Func<Person, string> cachedPropertyGetter = Person.CreatePropertyGetterExpression(); |
|
|
|
[Benchmark] |
|
public string CachedExpression() |
|
{ |
|
return $"{cachedPropertyGetter(p)}"; |
|
} |
|
|
|
[Benchmark] |
|
public string ExpressionDelegate() |
|
{ |
|
var propertyGetter = Person.CreatePropertyGetterExpressionDelegate(); |
|
|
|
return $"{propertyGetter.DynamicInvoke(p)}"; |
|
} |
|
|
|
private static readonly Delegate cachedDelegate = Person.CreatePropertyGetterExpressionDelegate(); |
|
|
|
[Benchmark] |
|
public string CachedExpressionDelegate() |
|
{ |
|
return $"{cachedDelegate.DynamicInvoke(p)}"; |
|
} |
|
} |
|
|
|
public class Person |
|
{ |
|
public string Name { get; set; } |
|
|
|
public static PropertyInfo GetPropertyInfo() |
|
{ |
|
return typeof(Person).GetProperty(nameof(Name)); |
|
} |
|
|
|
public static Func<Person, string> CreatePropertyGetterExpression() |
|
{ |
|
ParameterExpression arg = Expression.Parameter(typeof(Person), "x"); |
|
Expression expr = Expression.Property(arg, nameof(Name)); |
|
|
|
var propertyGetter = Expression.Lambda<Func<Person, string>>(expr, arg).Compile(); |
|
return propertyGetter; |
|
} |
|
|
|
public static Delegate CreatePropertyGetterExpressionDelegate() |
|
{ |
|
ParameterExpression arg = Expression.Parameter(typeof(Person), "x"); |
|
Expression expr = Expression.Property(arg, nameof(Name)); |
|
|
|
var propertyGetter = Expression.Lambda(expr, arg).Compile(); |
|
return propertyGetter; |
|
} |
|
} |