Dynamic methods in .NET


Using reflection to invoke methods which are not known at compile time might be problematic in performance critical applications. It is roughly 2.5-3.0 times slower than direct method calls. Here’s a sample test I’ve conducted:

Here are the results:

Method CPU units
Direct method invocation 796
Reflection method invocation 1986

So using reflection to perform a single property read is 2.5 slower than direct property access.

Dynamic methods can be used to generate and execute a method at run time, without having to declare a dynamic assembly and a dynamic type to contain the method. They are the most efficient way to generate and execute small amounts of code. Here’s an example of using DynamicMethod class to generate a getter for a given property:

Now using this method we can emit a getter method from a PropertyInfo at run time and execute the returned delegate:

And here are the final results I’ve obtained using three different methods to read a property value:

Method CPU units
Direct method invocation 796
Dynamic method invocation 1190
Reflection method invocation 1986

Leave a comment

Your email address will not be published. Required fields are marked *