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

前端 未结 5 1551
死守一世寂寞
死守一世寂寞 2021-01-02 16:08

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.

相关标签:
5条回答
  • 2021-01-02 16:55

    Delegate.CreateDelegate

    Probably the best docs on MSDN :)

    0 讨论(0)
  • 2021-01-02 16:56

    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.

    0 讨论(0)
  • 2021-01-02 17:01

    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 讨论(0)
  • 2021-01-02 17:05

    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

    0 讨论(0)
  • 2021-01-02 17:08

    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.

    0 讨论(0)
提交回复
热议问题