prosseek
prosseek

Reputation: 190659

Speeding up Reflection API with delegate in .NET/C#

This post has the comment if you need to call the method multiple times, use reflection once to find it, then assign it to a delegate, and then call the delegate..

ADDED

I came up with an example of using delegate here.

Upvotes: 7

Views: 3829

Answers (5)

deostroll
deostroll

Reputation: 11975

Isn't it obvious. You load the assembly into your app domain; create an instance of the type, and then create a delegate pointing to that instance's method...

Upvotes: 1

Neowizard
Neowizard

Reputation: 3017

Fist off, this is not caching. You are not saving a copy of the method in a "closer" location, you're just holding on to a reference to that method.

Think about the steps needed to take in order to call a method using reflection (accessing the reflation data from the assembly, looking up the method/namespace/class by name and more...), the last step is getting a reference (and don't let anyone tell you that a delegate is a pointer!) to the method and invoking it. When you use a delegate you only take the last step, and save yourself all that headache that comes with reflection.

Upvotes: 1

Haris Hasan
Haris Hasan

Reputation: 30097

Obviously it will work faster because of the reduced overheard caused by reflection. If you follow the tip, you won't go for reflection each time rather you will store reference in a delegate and hence you are reducing cost by not redoing the reflection. So yes, it will act like caching i guess once you are storing reference in a delegate in a sense that you won't have to go to reflection again

Upvotes: 1

leppie
leppie

Reputation: 117220

Delegate.CreateDelegate

Probably the best docs on MSDN :)

Upvotes: 1

Brandon Moretz
Brandon Moretz

Reputation: 7621

A delegate is simply a pointer to a function. If you're using reflection (at all) there is generally a lot of overhead associated with it. By finding this methods address once and assigning that address to your delegate variable, you are in effect caching it.

So, it's not the "delegate" type that works faster, it's just that you're "computing" once and "using" it multiple times that grants you the speed increase.

Upvotes: 4

Related Questions