Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leak in JavaScript (Chrome)

I'm calling a function 50 times a second, which does some expensive things as it is painting alot on a <canvas> element.

It works great, no problems there, but I just took a look at the memory usage and it was stealing 1MB a second of my RAM. Chrome seems to garbage collect, as it went down each minute or so, but then the usage grew again.

What I tried is putting return at certain places in my function so as to decide what part of my function exactly causes the leak. I've been able to cut it down to a specific line of code, after which the evil part comes, but I don't really know how to solve it.

My questions are:

  • What tool is available to effectively measure JavaScript memory leaks in Chrome?
  • Would it be effective to set variables to null / undefined after they have been used, something like disposing them?

If the source code is really necessary I wouldn't hestitate to post it here, but I must admit that it's both long and perhaps a little ununderstandable for others.

like image 988
pimvdb Avatar asked Mar 03 '11 14:03

pimvdb


1 Answers

I'm just going to pull this quote directly, linked from the article;

Speaking of memory leaks, breaking circular references — the cause of the leaks — is usually done with simple null assignment. There’s usually no need to use delete. Moreover, null‘ing allows to “dereference” variables — what delete would normally not be able to do.

var el = document.getElementById('foo');
// circular reference is formed
el.onclick = function() { /* ... */ };
// circular reference is broken
el = null;
// can't `delete el` in this case, as `el` has DontDelete

For these reasons, it’s best to stick with null‘ing when breaking circular references.

delete Explained

like image 77
Andrew Avatar answered Sep 24 '22 03:09

Andrew