Why does reflection not perform well in .NET?

.net, performance, reflection

Solution

Reflection performs well, it just does a lot more than static code.

Say you have this code snippet:

typeof(SomeClass).GetMethod("SomeStaticMethod").
Invoke(null, new object[] { 1, 2, 3 });

This is the same as this:

SomeClass.SomeStaticMethod(1, 2, 3);

But it should be obvious that the first one has a lot more work to do. It has to get type information, traverse it to see if there's a SomeStaticMethod method, check what kind of method it is, invoke the method on an instance, or not if it's static and pass the object array is parameters, boxing/unboxing the integers in this case as well.

And this is probably a very broad summary, there's no doubt even more going on. Yet despite this, reflection is still very fast and used in a lot of areas, from databinding on WinForms to model binding in ASP.NET MVC (every request you make to this site, built on MVC, involves a whole bunch of reflection and yet, the site is very fast and MVC is regarded as a very fast framework).

Problem

I am interested to know the technical reasons: why does reflection not perform well in .NET?

Original source