Why does this JavaScript cause a memory leak? - javascript

The following code is regarded as causing a memory leak because element maintains a reference to function bar and bar maintains a reference to element via closure (if I understand correctly).
Why does this cause a memory leak? Does it only cause a leak when element is a DOM node?
function foo(element, a, b) {
element.onclick = function bar() { /* uses a and b */ };
}

This is called a Javascript closure and is an expected feature of Javascript. This is not a memory leak in any modern browser.
If the DOM element represented by element is removed from the DOM, then the onclick handler will be garbage collected and then the closure itself will be garbage collected.
During the lifetime of element, the variables a and b will be part of the closure. This is an expected language feature as they are part of the closure that this code creates. When and if, element is deleted from the DOM and it is garbage collected, the closure and its references a and b will be eligible for garbage collection too.
There are some old browsers that did not always handle this properly, but that is generally not considered a design consideration any more for modern browsers. Further, it only caused an issue of consequence if you ran code like this over and over (removing DOM elements each time too) such that a large enough amount of memory was consumed by things that weren't being garbage collected when they should have been. This typically only happened in long running single page applications that had a lot of dynamic DOM stuff going on. But, as I said with modern browsers, this is no longer an issue as the browser's garbage collector handles this situation now.

This code only caused a memory leak in certain old versions of Internet Explorer. Internet Explorer 8 made some changes to memory management which mitigated the problem:
https://msdn.microsoft.com/en-us/library/dd361842(v=vs.85).aspx
As all of the affected versions of Internet Explorer are now thoroughly obsolete, this is no longer an issue you need to be concerned with.

Related

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 element from the dom tree, the object still exist in memory?
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.
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.

JavaScript / jQuery memory usage within a browser

To what extent are jQuery / JavaScript functions stored in memory?
Once the browser has parsed the page, does it go into memory? All of it? If functions are repeatedly called, are they always from memory?
If the portion of memory allocated to scripts is filled (thinking Internet Explorer 6 on a horrible PC here), what happens? (Other than a slow browser...)
Is there a way of seeing how much memory is used by a variable or a function as a whole?
As per my knowledge, once JavaScript code has been parsed by the browser, objects remain in the memory unless dereferenced and garbage collected. Garbage collection is dependent on the JavaScript implementation of the browser though.
You can see the memory usage by JavaScript objects easily in Chrome. See here.

Do i need to delete dom fragments or will the garbage collector remove them?

This maybe a bit of a silly question. I'm assuming that the garbage collector disposes of any dangling variables after a function ends execution, but I was wondering if this also applies to DOM fragments.
If I create a DOM fragment or any unattached node for that matter, will the garbage collector delete it after the function has finished execution?
//would this create a memory leak?
setInterval(function exampleScope() {
var unusedDiv = document.createElement('div');
}, 10);
I know this example is useless but its the simplest form of the pattern I'm worried about. I just want to know I'm doing the right thing. I've been hard at work building a very high performance JavaScript game engine, Red Locomotive. I don't want to add any memory leaks.
There is an IE 7 memory leak with DOM elements in event handlers: jQuery leaks solved, but why?
With other browser you should be fine. See Freeing memory used by unattached DOM nodes in Javascript.
If you worry much about memory leaks and care for your tech illiterate IE users, you should read this: Understanding and Solving Internet Explorer Leak Patterns
Well, it's not 100% conclusive but I made a quick JSFiddle to experiment with this. This is a tight loop that runs your code above 100000000 times. Using the Chrome Task Manager memory usage jumped from 47.9MB to 130MB and stayed fairly constant until completed, where it dropped down to 60MB ish.
http://jsfiddle.net/u7yPM/
This suggests that the DOM nodes are definitely being garbage collected, else the memory usage would continue increasing for the whole run of the test.
EDIT: I ran this on Chrome 14.

how do we test if `div.innerHTML=""` will hog the memory until the page refreshes or the browser is closed?

I'm suspecting that if i set div.innerHTML="" instead of using while(div.firstChild)div.removeChild(div.firstChild) the memory will be hogged until the page refreshes or the browser closes.
My question is how do we actully go about testing if my hypothesis is true?
Firstly, whether memory is returned to the system or not depends on the Javascript garbage collector (gc) and therefore results will vary from browser to browser.
It's difficult to measure memory usage by looking at the process as there are several layers of memory management in place. To see how this can have an impact, consider that a huge javascript object might have been erased forever, but that memory might still not have yet been released back to the operating system because the web browser might keep hold of it in case you need to create more big objects. Another example is that most gc routines only run periodically, so it's possible that object is still in memory but will be reclaimed later.
However, it's pretty easy to determine if a particular operation is leaking memory as all you have to do is repeat it in an endless loop. e.g.
remove references to existing html elements
construct new html elements
add them to the page
Try this code:
var div = document.getElementById("test")
while(true) {
// remove operation, change me
while(div.firstChild) {
div.removeChild(div.firstChild);
}
// create some new content
for(var i=0; i<1000; i++) {
var p = document.createElement('p');
p.appendChild(document.createTextNode('text'));
div.appendChild(p);
}
}
My results in Chrome, using the Task Manager (shift+esc):
Leaving the loop running endlessly without deleting anything eventually results in the "Aw! Snap" screen, which indicates memory has been exhausted
Using the removeChild technique leads to memory usage stabilizing at around 750MB
Using the innerHTML technique leads to memory usage stabilizing at around 750MB
If memory isn't leaking you'll notice a pattern similar to this: Increases to 300, drops to 150, increases to 400, drops to 250, eventually stabilising. This is the memory management system running out of memory, triggering the gc to reclaim memory that has been deallocated and increasing the available memory footprint each time until reaching a soft limit that has been set to avoid the process impacting others. This is a typical memory management scheme and more can be found by reading this wikipedia article: http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)
Since both results stabilize, I'd conclude that (for Chrome at least) both techniques work the same though you might get different results from other browsers.
As there doesn't seem to be a difference, removeChild should be preferred as innerHTML is not included in the W3C standard and is frowned upon by some developers. See more here: Alternative for innerHTML?
The reason innerHTML and removeChild have no differences is because underneath, they both have to de-reference elements to stop them from being visible on the screen. Memory leaks are most likely to occur when you have circular references (A points to B, B points to A, nobody else points to either) but this is only a problem in older browsers. This link has some good guidelines about how to avoid js memory leaks: Javascript memory management pitfalls?

Javascript memory leaks after unloading a web page

I have been reading up to try to make sense of memory leaks in browsers, esp. IE. I understand that the leaks are caused by a mismatch in garbage collection algorithms between the Javascript engine and the DOM object tree, and will persist past. What I don't understand is why (according to some statements in the articles I'm reading) the memory is not reclaimed after the page is unloaded by the browser. Navigating away from a webpage should put all the DOM and javascript objects out of scope at that point, shouldn't it?
Here's the problem. IE has a separate garbage collector for the DOM and for javascript. They can't detect circular references between the two.
What we used to was to clean up all event handlers from all nodes at page unload. This could, however, halt the browser while unloading. This only addressed the case where the circular reference was caused by event handlers. It could also be caused by adding direct references from DOM nodes to js objects which had a reference to the DOM node itself.
Another good thing to remember is that if you are deleting nodes, it's a good idea to remove the handlers yourself first. Ext-js has a Ext.destroy method that does just that (if you've set the handlers using ext).
Example
// Leaky code to wrap HTML elements that allows you to find the custom js object by adding
//a reference as an "expando" property
function El(node) {
this.dom = node;
node.el = this;
}
Then Microsoft hacked IE so it removed all event handlers and expando properties when unloading internally, therefore it's much faster than doing it with js. This fix seemed to fix our memory problems, but not all problems as there are people still having the problem.
MS's description of the problem
MS releases patch that "fixes" memory leaks:
Blog about fixed memory leaks
IE still has some problems
At our company, we use ext-js. By always setting event handlers using ext-js, which has a an internal clean up routine, we have not experienced memory leaks. In reality, memory usage grows but stops at about 250Mb for a machine with 4Gb of RAM. We don't think that's too bad since we load about 2Mb(uncompressed) of js files and all the elements on the page are dynamic.
There's a lot to be said about this and we've researched this extensively where I work. Feel free to ask a more specific question. I may be able to help you.
The best thing I ever read about Javascript memory leaks was written by Doulgas Crockford.
To answer your question, yes, the browser absolutely should unload all the objects (and most importantly, event handlers) at the appropriate time. If it did, it wouldnt have leaks :)
You don't have to make sense of them -- they are bugs in broswers and being fixed from versions to versions.

Categories

Resources