Do lambda expressions create garbage?

Does a C# lambda expression passed to a Func argument create garbage? …on Windows desktop / .NET 4.5? Does the answer vary per platform?

What’s the current / best / easiest approach to answering this type of question (“does doing X create garbage?”) on Visual Studio 2015?

StackOverflow says yes: linq - C# Does Lambda => generate garbage? - Stack Overflow

StackOverflow probably :slight_smile:

It isn’t entirely true to just answer this as a “yes”. Lambdas create garbage only when they have to.

So, when do they have to create garbage? When the lambda captures any variables from the outside scope. There is a very simple pattern that can be used to avoid the allocations (assuming you have control of the source that calls the lambda): let any method that takes in a lambda also take in a context object. That context object would then be passed to the lambda (which is now just a static method and thus creates no trash) and the lambda should only access data via the context.

The easiest (and only accurate) way to know what creates trash is to just use a profiler. It knows the correct answer 100% of the time.

1 Like

Right, I should have said that in my post, sorry if that confused anyone!