2y ago · Jul 19, 2024 6:20 PM
Standard takes ~25 nanoseconds and causes boxing on value types. Compiling a down to a raw delegate executes in **0.8 nanoseconds**!
Generating a high-speed property getter delegate with ILGenerator:
CODE
PropertyInfo.GetValue() CODE
DynamicMethodGenerating a high-speed property getter delegate with ILGenerator:
CSHARP
using System;
using System.Reflection;
using System.Reflection.Emit;
public static class FastPropertyAccessor
{
public static Func<TTarget, TProperty> CreateGetter<TTarget, TProperty>(PropertyInfo property)
{
MethodInfo getMethod = property.GetGetMethod(nonPublic: true)!;
DynamicMethod dynamicMethod = new DynamicMethod(
name: $"Get_{property.Name}",
returnType: typeof(TProperty),
parameterTypes: new[] { typeof(TTarget) },
restrictedSkipVisibility: true
);
ILGenerator il = dynamicMethod.GetILGenerator();
il.Emit(OpCodes.Ldarg_0); // Load target instance
il.Emit(OpCodes.Callvirt, getMethod); // Call getter
il.Emit(OpCodes.Ret); // Return value
return (Func<TTarget, TProperty>)dynamicMethod.CreateDelegate(typeof(Func<TTarget, TProperty>));
}
}
ReflectPro · Reflection & Roslyn
C# source generators, Expression Trees, and runtime IL emiss...
C# source generators, Expression Trees, and runtime IL emiss...
The following users thanked ReflectPro for this post: