JavaScript中的内存泄漏(Chrome) [英] Memory leak in JavaScript (Chrome)

查看:152
本文介绍了JavaScript中的内存泄漏(Chrome)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我每秒调用一次函数50次,因为它在< canvas> 元素上绘制了很多昂贵的东西。



它效果很好,没有问题,但我只是看看内存使用情况,它偷了我的RAM一秒钟1MB。 Chrome浏览器似乎垃圾收集,因为它每分钟左右都会下降,但随后使用量再次增长。



我试着把 return 在我的函数的某些地方,以决定我的函数的哪一部分确切地导致泄漏。我已经能够将它缩减为特定的代码行,然后是邪恶部分,但我不知道如何解决它。



我的问题是:


  • 有什么工具可以有效地测量Chrome中的JavaScript内存泄漏?

  • 在使用它们之后将变量设置为 null / undefined 会有效吗? li>


如果源代码真的有必要,我不会在这里公布它,但我必须承认它很长,也许是一点点对于其他人来说,这是不可理解的。

解决方案

b
$ b


说到内存泄漏,打破循环引用 - 泄漏的原因 - 通常使用简单的空赋值来完成。通常不需要使用删除。此外,null'ing允许取消引用变量 - 删除通常无法执行的操作。




  var el = document.getElementById('foo'); 
//循环引用形成
el.onclick = function(){/ * ... * /};
//循环引用被破坏
el = null;
//在这种情况下不能`删除el`,因为`el`有DontDelete



< blockquote>

由于这些原因,最好在打破循环引用时坚持使用null。

< a href =http://perfectionkills.com/understanding-delete/ =noreferrer> 删除解释


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.

解决方案

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

这篇关于JavaScript中的内存泄漏(Chrome)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆