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 DO开发者_如何学PythonM 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.
精彩评论