views:

326

answers:

3

I've just discovered that when the remove() function is used, the matched elements are not removed from the jQuery object, just the DOM.

According to the remove() documentation:

Removes all matched elements from the DOM. This does NOT remove them from the jQuery object, allowing you to use the matched elements further.

Surely if a web app keeps on adding and removing elements from the dom, this will keep using up more and more memory? Can someone confirm if this is the case? What can be done to avoid this?

+1  A: 

The issue of a memory leak seemed to already been brought up to the jQuery team http://groups.google.com/group/jquery-dev/browse_thread/thread/4a99f6e9b2e33057/45ce657a48afd43a

RedWolves
I don't think that leak discussion (although interesting) is the same thing andyuk's talking about.
Nosredna
+7  A: 

I think that it would be garbage collected (eventually) once it falls out of scope. If you're having problems with excessive memory use, though you might try using the delete operator on the returned object.

tvanfosson
Yes. The DOM is altered but the jQuery object is not. If you assigned the jQuery object to a variable, the garbage collector should have a shot at that variable when it falls out of scope.
Nosredna
+2  A: 

I have tried to find the answer to my own question by doing a little test.

<script type="text/javascript">
$(document).ready(function() { 
    for ($i=1; $i<10000; $i++) {
     $('table').append("<tr id=\"test_" + $i + "\"><td>test " + $i + "</td></tr>");
     $('#test_'+($i-1)).remove();
    }
});
</script>
<table>
    <tr><td id="test_0">test 0</td></tr>
</table>

I did variations on the remove() by using:

var test = $('#test_'+($i-1)).remove();

and with the delete operator (thanks to tvanfosson's suggestion):

var test = $('#test_'+($i-1)).remove();
delete test

Having done these tests I would still just use remove(). Its very hard to tell if there was a memory leak since the memory usage of the browser always increased after reloading the page. Perhaps someone else is able to provide a more conclusive answer by testing the code differently.

andyuk