开发者

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

开发者 https://www.devze.com 2023-03-14 06:57 出处:网络
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 del开发者_运维技巧egate, and then call the delegate..

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 del开发者_运维技巧egate, and then call the delegate..

  • How and why does this delegate work faster? Can anyone has some example?
  • Can I call this caching? If so, are there any other method than this caching method with delegate?

ADDED

I came up with an example of using delegate here.


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.


Delegate.CreateDelegate

Probably the best docs on MSDN :)


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


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.


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...

0

精彩评论

暂无评论...
验证码 换一张
取 消