Delegates, Actions and Memory Allocations

c#, delegates

Solution

It doesn't matter whether you explicit use `new SomeDelegate` or omit it, whether you use a lambda, the `delegate` keyword, or pass in a method group, or any possible solution you haven't shown. In every single case a delegate object will be created. The compiler can often infer that it should be there, so it doesn't force you to type it out; but the creation of that delegate is still happening no matter what. (Well, technically you could pass in `null` and not allocate an object, but then you can't ever do any work, so I think it's safe to ignore that case.)

The only real difference in memory allocations between each of the options is that in the given anonymous method blocks you are closing over a variable (`workfinished`). In order to create that closure the runtime will generate it's own type to store the state of the closure, create an instance of that type, and use that for the delegate, so all of the solutions using an anonymous method are creating one new object. (Granted, it's small, so it's not going to be particularly expensive in most situations.)

Problem

I'm currently working on a chunk of code that requires minimum memory allocations. I've noticed if I use a method for a parameter the compiler changes the code and creates a new `Action`, but if I use an anonymous method the compiler creates a delegate block. I'm aware that the new `Action` allocates memory, but I'm not so sure about the delegate. Will delegates allocate memory when used? My code: ``` bool workfinished = false; void DoWork() { MyMethod(CallBack1Work, ()=>{ workfinished = false;}); } void MyMethod(Action callback1, Action callback2) { } void CallBack1Work() { } ``` Compiler version: ``` bool workfinished = false; void DoWork() { MyMethod(new Action( CallBack1Work ), delegate{ workfinished = false;}); } void MyMethod(Action callback1, Action callback2) { } void CallBack1Work() { } void DoWork_b01() { workfinished = false; } ```

Original source

Related problems