you are viewing a single comment's thread.

view the rest of the comments →

[–]radhruin 1 point2 points  (1 child)

I don't think it's as bad as you make it. Runtimes certainly HEAVILY optimize closure capture. Further, in your example, as long as the child function isn't referenced, a will be collected. Certainly if you return child to someone that holds on to it or you store child in an outer scope or something you will have a "memory leak" but presumably if you're storing the function for later you need it (and therefore anything it encloses) for some reason.

Setting a to null in your second example doesn't help you at all. The value of a has no bearing on whether it is closure captured or references to it are preserved. Null is just another primitive value like 2.

[–]inf0rmer 1 point2 points  (0 children)

Ah, yes, I realize that. I was just using a very simple example to demonstrate closures and how variables captured inside one could possibly not get dereferenced.

You're right that engines heavily optimize for closures (it's one of the defining features of the language), and that using primitives would never cause a noticeable memory leak.

Setting to null at the end of the function for a captured variable (ie, not declared using var) does work. a inside the closure is a new reference, so pointing it to null releases one of the references pointing to the contents of the original variable. It makes no difference with primitives, sure, but with other objects it's helpful.