Home / Forums / Writing High-Speed Dynamic Delegates with Reflection.Emit & DynamicMethod in .NET

UnreliableCode Community

Developer Research, Reverse Engineering & Coding Community

Source

Writing High-Speed Dynamic Delegates with Reflection.Emit & DynamicMethod in .NET

ReflectPro
Reflection & Roslyn
MEMBER
Rep: 355
Join Date: Mar 2022
Posts: 9
Thanks: 75
2y ago · Jul 19, 2024 6:20 PM
#1
Standard
CODE
PropertyInfo.GetValue()
takes ~25 nanoseconds and causes boxing on value types. Compiling a
CODE
DynamicMethod
down to a raw delegate executes in **0.8 nanoseconds**!

Generating 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...
The following users thanked ReflectPro for this post:
CSharpNinja
Senior .NET Developer
VIP
Rep: 329
Join Date: Jan 2020
Posts: 16
Thanks: 75
2y ago · Jul 19, 2024 7:30 PM
#2
DynamicMethod generation is the secret sauce behind Dapper and AutoMapper's incredible speed. You pay the IL compilation cost once on startup, and then subsequent invocations execute at native direct-call speeds!
CSharpNinja · Senior .NET Developer
C# enthusiast, building distributed backend services and hig...
SourceGenDev
C# Tooling
MEMBER
Rep: 158
Join Date: Jan 2020
Posts: 8
Thanks: 79
2y ago · Jul 21, 2024 12:30 AM
#3
You can also achieve similar speeds using
CODE
Expression.Compile()
if you prefer strongly typed expression trees over raw IL opcodes.
SourceGenDev · C# Tooling
Metaprogramming with C# 9+ Source Generators and Roslyn Anal...