[thelist] JS memory leak detection?

liorean liorean at gmail.com
Mon Oct 24 05:16:44 CDT 2005


On 10/24/05, VOLKAN ÖZÇELİK <volkan.ozcelik at gmail.com> wrote:
>
> One final notice:
> IE's problem is not 100% related to circular references (using
> circular references just makes the issue more apparent)


As I said, it just needs to cross the COM/JScript border several times,
doesn't have to be circular. Just needs all COM objects you want to leak to
contain a JScript reference to another COM element that cannot be garbage
collected. You can build a long chain of COM elements that eventually links
a single COM element that contains a self reference, and all of them will be
impossible for iew to garbage collect.

Here is a sample with no circular refs:
>
> window.onload=function(evt){
> var element = document.getElementById("my-element");
> element.attachEvent("onclick",function(){});
> element.bigString=new Array(1000).join(new Array(200).join("XXXXX"));
> };
>

Wrong, there is a circular reference in there. The anonymous function closes
over the evt and element variables, thereby creating your circular
reference. To prove this, test setting the element variable to null at the
end of the onload function and then test it for leaks again.

window.onload=function(evt){
> var element = document.getElementById("my-element");
> var fnc=function(){var ele=document.getElementById("my-element2");};
> element.addEventListener("click", fnc, false);
> /*Make sure we see the leak*/
> element.bigString = new Array(1000).join(new Array(200).join("XXXXX"));
> };


I'm intrigued as to why this causes a leak in moz but not the first code.
The only thing I can see that could possibly cause this is that fnc closes
not only over the element reference but also over itself. If I were to guess
I'd say we're seeing a smarter garbage collector, able to catch direct
circular references, but not indirect circular references.

Altough there is no circular reference to "my-element" (the function
> is refering to node "my-element2" not "my-element") Mozilla shows some
> leak (much less than IE but it leaks anyway) on the long run as well.
>

No. The reference to my-element2 is not persistent, it will disappear
directly after the function has been called. It's the reference to
my-element, or perhaps to the function that references my-element, that is
the circular reference.



When working with nested functions like this, you'll soon see that it's the
local variables outside the function that matters, not the contents. The
contents are not persistent and would only cause leaks if the function
itself preserves an inner function after it's been run.
--
David "liorean" Andersson
<uri:http://liorean.web-graphics.com/>


More information about the thelist mailing list