Skip to content Skip to sidebar Skip to footer

JQuery Remove And Memory Leaks

Im working on a game, and ive seen a lot of memory consuption, im using jquery animate, and after the animation is done, i .remove() the element, my question is, after removing an

Solution 1:

Javascript is a garbage collected language. That means that an object in memory will be released when no code holds any references to it and (for a DOM object) it's not in the DOM. So, when you remove an object from the DOM, as long as no other part of your javascript has a reference to that DOM object, the DOM object will be cleaned up and it's memory returned to the available memory pool when the garbage collector gets a chance to run.

Keep in mind that when memory is freed by the garbage collector, it may not be returned to the system right away or ever. It may stay as memory allocated to the browser, but it will be available for use by other memory requests within the browser. So, freeing memory in your script won't necessarily make the total memory used by the browser go down.

It is only a memory leak if repeatedly carrying out the same operation over and over causes the total memory used by the browser to continually rise. Only then can you be sure that some memory is being permanently consumed by a "leak".

There are a number of nuances about garbage collection, particularly for older versions of IE, but for modern browsers, mostly what you need to keep in mind is that if you hold a reference to an object in your own javascript data structures, it will not be garbage collected. If you don't hold a reference to it and it's not in the DOM, it will be freed and its memory recycled.


Solution 2:

If there are no references to the element, garbage collection will clean it up on its next run. You're just fine using .remove, but don't bother worrying about the garbage collection.


Post a Comment for "JQuery Remove And Memory Leaks"