Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I don't really get the difference, in both cases the a,b will be stored somewhere no? I mean, when you return that function it references a and b as the original function would have and you've done absolutely nothing different.

Can someone explain this a little better?



The argument is that because in the first case, the closure is created in a scope where element, a, and b all exist. So element is available in the closure even if it's never used.

Since now element has a property which closes over element, he argues this is a circular reference, which will eventually become a memory leak.

It seems to me that a smart JS engine could avoid this by noticing that there's no possibility of using element within the first closure, but I'm not an expert. Also it seems like a small price to pay unless you are constantly creating and destroying such widgets; surely anything associated with an unloaded page can be GC'ed regardless of circular references?


> It seems to me that a smart JS engine could avoid this by noticing that there's no possibility of using element within the first closure, but I'm not an expert.

They don't even need that. Any garbage collection strategy (including refcounting) have no trouble reclaiming cycle (the only GC type which may have problems are refcounting GCs, and they usually have a cycle detector for exactly that purpose).

The only way for this issue to arise is to involve two runtimes, each with its own garbage collector, able to create references between one another.

A cycle crossing the boundary will not be detectable by either GC, and will lead to a leak.

This is exactly what happens in Internet Explorer up to (and including) version 7: JavaScript lives in the jscript engine and the DOM lives in COM, each has its own GC, and they can have references to objects living in the other runtime.


And all of it stems from the fact that, JavaScript being a dynamic language, there's no way to statically determine whether the function will use 'element' or not (it could always eval() something evil and sneaky). Most functional languages would avoid packing 'element' at compile time, and I suspect that modern JavaScript compilers also handle this optimization whenever they can afford it.


I've found that when I use the webkit inspector, those unused values don't show in the Closure section of the Scope Variables display, and if I put a breakpoint in there and try to reference the unused variables I get a Reference Error.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: