Possible Memory Leak in remove() and empty()
Hey all,
I believe I have found a leak and have the beginnings of a solution to
it.
I'm writing an app that preforms ajax searching that returns pretty
large result sets. I render them via jQuery into a tbody. once a
subsequent search is performed I call tbody.empty() and append the new
results. I created a test harness that would perform a predefined
search 5000 times in a row with a good amount of time in between.
I noticed that IE was allocating quite a bit of memory and never
reclaiming it. At first I thought it was a closure or circular
reference on my part. Once I was sure I had removed them I ran more
test, sure enough it was still allocating a lot of memory. Through a
lot of research I found this article http://www.scribd.com/doc/2159768/Ajax-Part2
which says that JS's removeChild will leak in IE. Microsoft uses
another method to remove which is essentially this:
function DestroyElement(elem) {
var garbageBin =
document.getElementById('IEMemoryLeakGarbageBin');
if(garbageBin === undefined) {
garbageBin = document.createElement("DIV");
garbageBin.id = "IEMemoryLeakGarbageBin";
garbageBin.style.display = 'none';
document.body.appendChild(garbageBin);
}
garbageBin.appendChild(elem);
garbageBin.innerHTML = "";
}
I went through jQuery 1.2.6 and replaced the removeChild references
with a check for IE, and if so use this, else use the regular
removeChild. After doing so and rerunning my test I saw drastic
improvements in memory being reallocated after my elements were
removed from the document.
I also ran these test on FF, with or without this change it ran the
same way, recollecting memory correctly.
this is only seems to be a drastic performance increase if you are
creating 1000+ dom elements and binding events to them, but, the app I
am writing has to be able to run all day with out leaving or
refreshing the page.
I just thought the Dev team might be interested in my findings. I
plan on striping this down and writing conclusive tests and
documentation over the weekend.
-Chris