Kiran Vedula
Kiran Vedula

Reputation: 583

Reflection performance and interface

I heard on Jeremy Clark's pluralsight session on Reflection that performance of reflection can be increased by programming to interface.

That video doesn't explain why and how -- Can someone provide me pointers on why and how interfaces improve reflection performance

Upvotes: 0

Views: 265

Answers (1)

JDB
JDB

Reputation: 25810

On Slide 23 from Jeremy's "Practical Reflection in .NET" lecture (given in January, 2014), the following is presented:

  • Cast Types to a Known Interface
    All method calls go through the interface
    No dynamic method calls –no MethodInfo.Invoke
    Avoid interacting with private members

The basic idea is that it's better to use Reflection to find classes which implement a known interface then it is to find and directly use individual methods and properties. The reason?

  1. The fewer Reflection calls you have to make, the better. Each call to Reflection costs a lot of time (relatively speaking). It's much more effecient to make a single call to Reflection to get a class which implements a known Interface (from which point you can access members via the Interface) then it is to access each and every member via reflection.

  2. You can be reasonably confident that the class members associated with a known interface will behave in a particular way and not cause dangerous side effects. Arbitrarily grabbing methods and properties from a class based only on the name is extremely dangerous when dealing with third-party assemblies - you can't be reasonably certain that the method was meant to be used by you for your purpose.

Upvotes: 1

Related Questions