views:

109

answers:

6

My Javascript build a list of "LI" elements. When I update the list memory usage grows and never go down. I am wondering what should I do to remove DOM nodes without memory leak.

I tested in sIEve and it shows that browser keeps all elements which I thought was deleted by $.remove() or $.empty jQuery commands.

Help!!!

+1  A: 

Have you removed any event listeners? That can cause memory leaks.

Skilldrick
I even do for each element $(this).unbind().html("").remove();
podeig
+4  A: 

The DOM preserves all DOM nodes, even if they have been removed from the DOM tree itself, the only way to remove these nodes is to do a page refresh (if you put the list into an iframe the refresh won't be as noticable)

Otherwise, you could wait for the problem to get bad enough that the browsers garbage collector is forced into action (talking hundreds of megabytes of unused nodes here)

Best practice is to reuse nodes.

EDIT: Try this:

var garbageBin;
window.onload = function ()
    {
    if (typeof(garbageBin) === 'undefined')
        {
        //Here we are creating a 'garbage bin' object to temporarily 
        //store elements that are to be discarded
        garbageBin = document.createElement('div');
        garbageBin.style.display = 'none'; //Make sure it is not displayed
        document.body.appendChild(garbageBin);
        }
    function discardElement(element)
        {
        //The way this works is due to the phenomenon whereby child nodes
        //of an object with it's innerHTML emptied are removed from memory

        //Move the element to the garbage bin element
        garbageBin.appendChild(element);
        //Empty the garbage bin
        garbageBin.innerHTML = "";
        }
    }

To use it in your context, you would do it like this:

discardElement(this);
Andrew Dunn
I did not know about "The DOM preserves all DOM nodes, even if they have been removed from the DOM tree itself" Do you mean $.remove() function does not do anything?
podeig
How many MegaBite must be used to run garbage collector. I think 150Mb must be enough. But it does not work for me.
podeig
Edited, try supplied code.
Andrew Dunn
This is really interesting.
FK82
After testing in sIEve can I say that it helps to remove garbage nodes. But when I test in IE8 and FF anyway memory usage grows. Andrew, what appendChild does? Moves a node to the garbage div? Should I run $.unbind() before discadElement()?
podeig
A: 

Which browser do you use? And is this memory leak in all browsers?

Marcel de Kleine
A) This is a question, not an answer, B) the memory "leak" is consistent across all browsers as it simply behaves in the manner it is supposed to. Won't -1 because you are new.
Andrew Dunn
It happend in both IE8 and FireFox.
podeig
+1  A: 

The code below does not leak on my IE7 and other browsers:

<html>
<head></head>
<body>
    <a href="javascript:" onclick="addRemove(this)">add</a>
    <ul></ul>
    <script>
        function addRemove(a) {
            var ul = document.getElementsByTagName('UL')[0],
                li, i = 20000;
            if (a.innerHTML === 'add') {
                while (i--) {
                    li = document.createElement('LI');
                    ul.appendChild(li);
                    li.innerHTML = i;
                    li.onclick = function() {
                        alert(this.innerHTML);
                    };
                }
                a.innerHTML = 'remove';
            } else {
                while (ul.firstChild) {
                    ul.removeChild(ul.firstChild);
                }
                a.innerHTML = 'add';
            }
        }
    </script>
    </body>
</html>

May be you can try to spot some differences with your code.
I know that IE leaks far less when you insert first the node in the DOM before doing anything to it, eg: attaching events to it or filling its innerHTML property.

Mic
+1  A: 

This is more of an FYI than an actual answer, but it is also quite interesting.

From the W3C DOM core specification (http://www.w3.org/TR/DOM-Level-2-Core/core.html):

The Core DOM APIs are designed to be compatible with a wide range of languages, including both general-user scripting languages and the more challenging languages used mostly by professional programmers. Thus, the DOM APIs need to operate across a variety of memory management philosophies, from language bindings that do not expose memory management to the user at all, through those (notably Java) that provide explicit constructors but provide an automatic garbage collection mechanism to automatically reclaim unused memory, to those (especially C/C++) that generally require the programmer to explicitly allocate object memory, track where it is used, and explicitly free it for re-use. To ensure a consistent API across these platforms, the DOM does not address memory management issues at all, but instead leaves these for the implementation. Neither of the explicit language bindings defined by the DOM API (for ECMAScript and Java) require any memory management methods, but DOM bindings for other languages (especially C or C++) may require such support. These extensions will be the responsibility of those adapting the DOM API to a specific language, not the DOM Working Group.

In other words: memory management is left to the implementation of the DOM specification in various languages. You would have to look into the documentation of the DOM implementation in javascript to find out any method to remove a DOM object from memory, which is not a hack. (There is however very little information on the MDC site on that topic.)


As a not on jQuery#remove and jQuery#empty: from what I can tell neither of these methods does anything other than removing Objects from DOM nodes or removing DOM nodes from the document. That of course does not mean that there is no memory allocated to these objects (even though they aren't in the document anymore).

FK82
A: 

If you have to "post-fix" leakage, and must do so without rewriting all your code to take closures, circular references etc in account, use Douglas Crockfords Purge-method prior to delete:

http://javascript.crockford.com/memory/leak.html

Or use this closure-fix workaround:

http://laurens.vd.oever.nl/weblog/items2005/closures/

Jens