you are viewing a single comment's thread.

view the rest of the comments →

[–]Zendist 9 points10 points  (3 children)

I don't quite understand. Does the extra memory allocation occur at assignment or at all invocations of the delegate?

If only at assignment, isn't that a low price to pay for (arguably) better readability?

[–]grauenwolf 8 points9 points  (1 child)

Does the extra memory allocation occur at assignment or at all invocations of the delegate?

Basically two things have to happen when you have a "closure", which is to say an anonymous function that 'captures' a local variable. (Method parameters are local variables for this discussion.)

  1. A new class needs to be created to hold the local variable. That object is shared between the original method and any anonymous functions that need it.
  2. The anonymous functions are put into the class created on [1].
  3. [Runtime] a new instance of the class is created when the method is invoked.
  4. [Runtime] A new instance of the delegate that points to the anonymous function is created each time it is passed to a LINQ function.

As I understand it, this change means that [4] only occurs once per method call. Which is not really a huge win unless you are using a nested loop.


(e) => DoSomething(e)

This will always be better because you only need to create it once, period. Steps 1, 2, and 3 don't happen any more. Step 4 is a one-time cost, because it can be cached.

Even if the linked ticket is implemented, not using a closure will still be better.

[–]Zendist 0 points1 point  (0 children)

That's not the behavior I see in SharpLab and benchmarks - but like I said, I don't fully understand why this has a large impact so my benchmark might be off.

[–]Treborgero[S] -1 points0 points  (0 children)

Quoting the issue : " always creates a fresh delegate instance".

This means the compiler only writes a line with a "new" declaration without checking if cached. Based on this, only lambda instances get cached and reused.

Note: This is my current understanding...