Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of C# Lambda versus event handler

What if any is the performance advantages of using a Lambda to handle async callbacks versus an old-fashioned event handler?

I find that I use this pattern more because it allows me to access method-level data and it does not litter my code with methods:

this.Click += (s, e) => { MessageBox.Show(((MouseEventArgs)e).Location.ToString());};
like image 947
Keith Adler Avatar asked Mar 23 '11 17:03

Keith Adler


2 Answers

If your lambda does not use captured variables, it is equivalent to a static method that is invoked through the delegate. If you lambda does use captured variables, then an object (reference type) is created for you behind the scenes. This incurs an allocation and a subsequent GC cost. In most cases, the effect would be negligible, especially in your scenario which looks like a click event in a user-interface framework (the rate at which such events may occur is too slow for the method invocation choice to have any impact).

like image 23
Sasha Goldshtein Avatar answered Sep 28 '22 00:09

Sasha Goldshtein


A lambda is just a delegate that gets created by the compiler. In practical terms, it will perform exactly the same.

Technically, there will often be a (incredibly slight) performance decrease, as an extra class is created to handle closures, where a traditional "event handler" is typically just a delegate reference on the same class that's calling the event. If you don't close over any local variables, the two will have exactly the same performance characteristics. In your case, there is zero difference, as no extra class is generated, since you're not closing over a variable.

The main disadvantage to using a lambda is not performance, it is the inability to unsubscribe from the event.

like image 164
Reed Copsey Avatar answered Sep 27 '22 23:09

Reed Copsey