Replies: 1 comment 29 replies
-
As a default implementation, the closure is allocated on heap, so it is up to GC to clean them up, just as all reference objects. If you count that as a leak, then all reference objects also leak, before GC kicks in. Surely the compiler can do better (to not allocate on heap) in theory, but it is hard if the M2 is in another scope, and impossible if M2 is in another assembly, because the compiler need to prove that M2 does not store the reference to the lambda. That's one reason why local method feature was introduced, which makes it easier to do that optimization. |
Beta Was this translation helpful? Give feedback.
29 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
I noticed this question recently: How does lambda affects the exact lifetime of its captured objects?
Yes it should keep it alive in order to have access to it. But consider the code below:
Here
C y
is only temporarily used inM
, but its reference is carried by the closure that returns, as confirmed here. If the caller toM
holds a reference to the returned delegate, bothx
andy
would be alive, although no one should be able to accessy
any more.Isn't this considered to be a kind of memory leak? I imagine the problem will deteriorate for larger methods that use many lambdas (for example, for Linq).
Note that the spec says:
So the compiler seems to be obeying the spec.
Beta Was this translation helpful? Give feedback.
All reactions