[thelist] JS memory leak detection?

liorean liorean at gmail.com
Sun Oct 23 12:26:11 CDT 2005


On 10/23/05, aardvark <evolt at roselli.org> wrote:
>
> is attachEvent inherently a resource hog?
>

No. attachEvent behaves just fine and isn't inefficient.



To return to iewleaking memory, the problem with leaks is that when you
start referencing COM objects from JScript and JScript objects from COM
objects iew cannot garbage collect thos objects properly. To show you an
example of how easy it is to create such a reference, look at this:


var
coll=document.getElementsByTagName('td'),
i=0,
obj;
while(obj=coll.item(i++))
addSomeStupidListener(obj)

function addSomeStupidListener(obj){
obj.onmouseover=function(){
alert(this);
};
}



This code adds a circular reference to all table cells on the page. Where is
the reference? Well, addSomeStupidListener contains a formal parameter obj,
ie a local variable. The inner function closes over all local variables, ie
it closes over the obj variable. Since this variable will contain a
reference to the element the function is assigned to, this is a typical way
of how circular references get created. JS-->COM-->JS-->COM-->...

COM and JScript have separate garbage collectors that don't detect these
kinds of circular references, so they can't clean up properly.


Is there a way to solve this problem?
Yes, there is. A slight change like this will solve it, for this specific
case:


var
__reflist__=[],
coll=document.getElementsByTagName('td'),
i=0,
obj;
while(obj=coll.item(i++))
addSomeStupidListener(obj)

function addSomeStupidListener(obj){
obj.onmouseover=function(){
alert(this);
};
__reflist__.push(function(){obj=null});
}

window.onbeforeunload=function(){
while(__reflist__.length>0)
__reflist__.pop()();
};
--
David "liorean" Andersson
<uri:http://liorean.web-graphics.com/>



More information about the thelist mailing list