Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do delegates improve the performance of an application?

I am new to the delegates concept. I've learnt it is similar to pointers in C++. In its advantages, it mentioned effective use of delegates improves the performance.

Considering it's a pointer. How does it improve the performance of an application?

If anybody could explain this with a simple example, that would be helpful.

like image 865
thevan Avatar asked Dec 09 '13 12:12

thevan


2 Answers

Delegates aren't directly about improving performance - they are about abstracting invocation. In C++ terms, it is indeed like a method pointer.

Most uses of delegates are not related to performance. Let's be clear about that from the outset.

However, one main time this can be used to help with performance is that this allows for scenarios like meta-programming. The code (usually library code) can construct complex chains of behaviours based on configuration information at runtime, and then compile that information into a method via any of Expression, TypeBuilder or DynamicMethod (or basically any API that lets you construct IL). But to invoke such a dynamically generated method, you need a delegate - because your static IL that was compiled from C# can't refer to a method that didn't exist at the time.

Note that an alternative way to do this would be to use TypeBuilder to create (at runtime) a new type that inherits from a subclass or implements a known interface, then create an instance of the dynamically generated type, which can be cast to the expected API in the usual manner and invoked normally.

like image 83
Marc Gravell Avatar answered Oct 12 '22 22:10

Marc Gravell


Delegates do not have an significant positive or negative impact on the performance of your application. What they provide is a means of decoupling aspects of your application from each other.

Lets say you have a situation where class A calls B.foo(). A is now partially coupled to B. You might then have a situation where B needs to call A.bar(). You now risk tightly coupling the two together. If instead of exposing A to B, you instead provide bar as a delegate, then you have removed that coupling.

like image 38
David Arno Avatar answered Oct 13 '22 00:10

David Arno