avoid memory leak setting This = null ?
Hello Glen,
thanks for sharing your knowledge with us, this was pretty much helpful.
What about the memory leak?
Would it be enough if i set all properties of an object to null, the object itself to null and at least This to null? Would the garbage collector be able to destroy my original object and also the reference This?
Thanks+regards,
Christoph
Last edited Feb 9, 2009 12:41 PMReport abusive comment
+1Hide replies to this comment ▲
Hi Christoph,
That sounded like a good plan, so I put it to a test. I created an object with "var This = this" in it, then a destroy method that set This = null (you shouldn't be able to access that closure from outside the object, so you need a destroy method).
The HTML page itself created 500,000 instances and stuffed them into an array (window.cache); then I looked at the memory delta. Then the HTML page deallocated everything by calling the method that set This = null, and also set the window.cache reference to null, just as you suggested.
The results in Firefox 2 were promising. The initial memory consumption was about 43K, then it shot up to 373K. After deallocation and waiting a few minutes, the memory was back down to 86K. So not a total prevention of the memory leak, but not bad.
In IE7 and Chrome, the results were less promising. IE7's memory consumption shot up to 910K (!) and only came back down to 744K, and the tests were inconsistent as well. Collection seems to be immediate in IE but the memory leak is gigantic. I even added a line to set window.cache = null and this may have improved the result somewhat, but I was still left with 583K consumed. (The next test brought it to 374K. Weirdly inconsistent.)
Chrome never reclaimed memory, and I waited around about 20 minutes for the collector to run. However, it only ever consumed ~83K total memory (meaning it needed about 44K for those objects).
The good news (sort-of) is that both Chrome and IE reclaimed all the memory when I navigated to google.com after the test. (Firefox did not.)
Certainly an interesting test, but the end result is that (especially with IE) it seems that you can't get much of the memory back in a fully Ajaxian situation -- you have to navigate away at some point, or performance will certainly degrade.
But, like I said in the post, the vast majority of applications won't create that kind of consumption, so reclaiming closures isn't a huge issue most of the time.