Take the 2-minute tour ×

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());};
share|improve this question
Without actually looking at the C# spec in depth, my educated guess is that lambda expressions are compiler syntactic sugar for delegate methods, and there is no discernible difference in performance. In the specific code you posted (displaying a message box), performance is essentially irrelevant. –  Robert Harvey Mar 23 '11 at 17:29
add comment

2 Answers

up vote 6 down vote accepted

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.

share|improve this answer
An extra class is only created where it's needed - it's not needed in the example given. –  Jon Skeet Mar 23 '11 at 17:34
@Jon: Very true - I'll edit to be (even more) explicit about this, though. –  Reed Copsey Mar 23 '11 at 17:35
The inability to unsubscribe can result in some really hard to track down memory leaks, I know because it bit me the first time I decided to use lambdas for event handling. –  juharr Mar 23 '11 at 17:56
add comment

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

share|improve this answer
There's no need for a type if it only captures "this" - in which case the compiler will create an instance method and the delegate target will be "this". –  Jon Skeet Mar 23 '11 at 17:34
add comment

Your Answer


