你如何清除Javascript中的内存? [英] How do you clear memory in Javascript?

查看:152
本文介绍了你如何清除Javascript中的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

var Obj = function(){}; var X = new Obj();

X = null 正确清除内存?

这也是等价的吗?

var Obj = function(){}; 
var X   = {}; 
X.obj   = new Obj();
delete(X.obj);

编辑
看起来虽然删除了X.obj不会立即清除内存,这将有助于垃圾收集。如果我不删除X.obj,仍然会有一个指向对象的指针,因此GC可能无法清理它。

EDIT It would seem that although deleting X.obj would NOT immediately clear memory, it would help the garbage collection. If I don't delete X.obj, there would still be a pointer to an object and so the GC may not clean it up.

虽然我正在挑选@德尔南的回答,如果你正在阅读这篇文章,你应该也能找到Benubird的文章。

Although I'm picking @delnan's answer, if you're reading this you should def also catch Benubird's article.

我还注意到我不小心写了删除(X)而不是删除(X.obj) ) - 抱歉。

I also notice I accidentally wrote delete(X) originally instead of delete(X.obj) - sorry.

推荐答案

简短的回答是你没有。 删除只是删除一个引用(而不是你尝试使用它的方式,请参阅上面的链接 - delete 是这些语言特征之一,很少有人真正理解),仅此而已。实现为您清除了内存,但是当它(并且严格地说 - 这就是为什么人们不应该依赖于提供它们的GC语言中的终结器)时,这不是您的业务。但请注意:

The short answer is that you don't. delete simply removes a reference (and not in the way you try to use it, see the above link - delete is one of those language features few people actually understand), nothing more. The implementation clears memory for you, but it's not your business when (and even if, strictly speaking - this is why one shouldn't rely on finalizers in GC'd languages that offer them) it does. Note though:


  • 只有可以被证明无法访问所有代码的对象(即无法访问它)的对象才能被删除。从概念上讲,通常相当明显的是对谁的引用。你只需要注意何时处理大量的闭包,因为它们可能会捕获比你想象的更多的变量。另请注意,循环引用 正确清理。

  • 旧版(但遗憾地仍然使用)IE版本中存在一个错误,涉及JS事件处理程序和DOM的垃圾收集元素。谷歌(甚至可能是SO)应该有更好的记忆材料。

  • Only objects that can be proven to be unreachable (i.e. no way to access it) to all code can be removed. What keeps references to whom is usually fairly obvious, as least conceptually. You just need to watch out when dealing with lots of closures, as they may capture more variables than you think. Also note that circular references are cleaned up properly.
  • There's a bug in old (but sadly still used) IE versions involving garbage collection of JS event handlers and DOM elements. Google (perhaps even SO) should have better material on my memory.

从好的方面来说,这意味着你不会晃来晃去指针错误或(当然保存上述陷阱)内存泄漏。

On the plus side, that means you won't get dangling pointer bugs or (save of course the aforementioned pitfalls) memory leaks.

这篇关于你如何清除Javascript中的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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