Fast creation of objects instead of Activator.CreateInstance(type)

I did some benchmarking between these (I would write down the bare minimum details): public static T Instance() //~1800 ms { return new T(); } public static T Instance() //~1800 ms { return new Activator.CreateInstance<T>(); } public static readonly Func<T> Instance = () => new T(); //~1800 ms public static readonly Func<T> Instance = () … Read more

How to emit a Type in .NET Core

Here is SO post about creating a dynamic type in .NET 4. How to dynamically create a class in C#? And in the accepted answer is just one use of AppDomain. AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run); Here is another SO post about a replacement of DefineDynamicAssembly function in .NET core. Is there any replace of … Read more

Real world uses of Reflection.Emit

Expression.Compile essentially does this – that is key to some of LINQ. I am currently using reflection emit to re-write a serialization API – because sometimes reflection just isn’t good enough. As it happens this will also allow it to generate dlls (much like how sgen works), allowing fully static code (I’m hopeful this will … Read more

Why is Calli Faster Than a Delegate Call?

Given your performance numbers, I assume you must be using the 2.0 framework, or something similar? The numbers are much better in 4.0, but the “Marshal.GetDelegate” version is still slower. The thing is that not all delegates are created equal. Delegates for managed code functions are essentially just a straight function call (on x86, that’s … Read more

Curiosity: Why does Expression when compiled run faster than a minimal DynamicMethod?

The method created via DynamicMethod goes through two thunks, while the method created via Expression<> doesn’t go through any. Here’s how it works. Here’s the calling sequence for invoking fn(0, 1) in the Time method (I hard-coded the arguments to 0 and 1 for ease of debugging): 00cc032c 6a01 push 1 // 1 argument 00cc032e … Read more

Call and Callvirt

When the runtime executes a call instruction it’s making a call to an exact piece of code (method). There’s no question about where it exists. Once the IL has been JITted, the resulting machine code at the call site is an unconditional jmp instruction. By contrast, the callvirt instruction is used to call virtual methods … Read more

How to dynamically create a class?

Yes, you can use System.Reflection.Emit namespace for this. It is not straight forward if you have no experience with it, but it is certainly possible. Edit: This code might be flawed, but it will give you the general idea and hopefully off to a good start towards the goal. using System; using System.Reflection; using System.Reflection.Emit; … Read more