【问题标题】:Circular references in IE6 creating memory leaksIE6 中的循环引用造成内存泄漏
【发布时间】:2012-04-09 05:38:54
【问题描述】:

I've found that all of these scripts, while doing the same thing create memory leaks,问题是,为什么?

似乎是因为循环引用。

<script>
function runme() {
  var node = document.createElement("div");
  node.onclick = function() {
    node.style.background = "red";
  }
  document.body.appendChild(node);
}
</script>

<script>
function runme() {
  var node = document.createElement("div");
  node.onclick = function() {}
  document.body.appendChild(node);
}
</script>

<script>
var node = document.createElement("div");
document.body.appendChild(node);
function runme() {
  node.onclick = function() {}
}
</script>

<script>
var node = document.createElement("div");
node.onclick = empty;
document.body.appendChild(node);
function empty() {
}
</script>

【问题讨论】:

  • 到目前为止你发现了什么?
  • 我发现他们都这样做了。但我不知道为什么。

标签: javascript internet-explorer memory-leaks


【解决方案1】:

我不知道您是如何检测到泄漏的,但对我来说只有前 2 个示例会造成泄漏。(使用 sIEve 检测到)

原因:在 runme() 中,您为 node 创建了一个闭包。

当您在所有 4 个示例中都有泄漏时,您应该展示如何删除 node(这就是发生泄漏的时间点)

但是:解决方案是在移除元素之前移除事件:http://www.crockford.com/javascript/memory/leak.html

【讨论】:

    猜你喜欢
    • 2014-09-08
    • 2014-01-09
    • 2012-07-03
    • 2010-09-28
    • 2011-01-01
    • 1970-01-01
    • 2018-08-13
    • 2014-05-17
    • 1970-01-01
    相关资源
    最近更新 更多