April 06, 2008

Use delegate calls instead of MethodInfo.Invoke

Reflection operations may allow you to write flexible and extensible code, but some of them also come with a serious performance hit. Type inspection and dynamic method invocation are probably the most representative.

If you ever needed to make a lot of dynamic calls using MethodInfo.Invoke but you knew that most of the time you would be calling the same small number of methods, you've probably thought about caching the MethodInfo instances, thus saving time by not having to obtain them again and again through inspection (via Type.GetMethod).

An even better solution, however, would be to bind a delegate to each MethodInfo using Delegate.CreateDelegate, cache the delegates and perform all your calls using these delegates instead of MethodInfo.Invoke. Delegate calls are significantly faster than dynamic invocation so the increase in performance will be quite noticeable.

Here's a great article on reflection where you can read more about the Why and the How.


mouse with holes said...

thanks for the tip, I'm a bit confused though - I just read this thread:
seems up to date - could it be related with .NET version?

Vlad said...

What are you confused about, exactly? That thread confirms what I wrote in my post. :)