Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 338
prosseek Avatar asked Jun 21 '11 18:06

prosseek


People also ask

Is reflection bad for performance C#?

The use of reflection is not recommended due to its bad performance because of all the security checks being done when calling a method or iterating through an object's members. Let's take the class defined below. It is a simple class which has one integer property.

Why is reflection typically considered slow in C#?

Reflection is slower Because it involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed.

How do you call a delegate in C#?

Delegates can be invoke like a normal function or Invoke() method. Multiple methods can be assigned to the delegate using "+" or "+=" operator and removed using "-" or "-=" operator. It is called multicast delegate. If a multicast delegate returns a value then it returns the value from the last assigned target method.


1 Answers

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.

like image 52
Brandon Moretz Avatar answered Sep 18 '22 11:09

Brandon Moretz