1

上次我在 Google 研究内存泄漏、循环引用以及垃圾收集的工作原理。但一切都有些混乱。我知道垃圾收集以这种方式工作:

var a = {}; // a is only reference to this object
a = 5 /* now variable a is reference to "number" (other js object)
and now the first empty object has no reference,
so it is cleaned from the memory. */

那看起来很酷。但我看到在 IE 中有一个 JScript 对象和 COM 对象。如果 COM 和 JScript 中的对象之间存在循环引用,则存在内存泄漏(未清理的内存)。所以现在我很困惑,并做了一些简单的例子来展示我的理解,或者不理解:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div style="width: 30px;" id='myDiv'></div>
    <script language='javascript'>
    "use strict";
     var a = 4,
     i,
     div = document.createElement('div');

     //no leaks
     function noLeaks(b) {
         this.a = a;
         a = this.b;
     }
     var obj = new noLeaks(5);

     //leak pattern
    function makeLeaks(func) {
        div.badAttachToCOMObject = func; // the problem is here
    }
    makeLeaks(function(){}); //attach reference to JScript objcet/function?


    //no leaks
    function size() {
        return '30px'; //just a value
    }
    function noStyleLeaks() {
        div.style.width = size();
        /* DOM (COM in IE) element just get a value,
        not a reference, only if I put a object or
        function to the value is a problem? */
    }
    noStyleLeaks();

    //leaks or not
    function styleLeaks() {
        div.style.width = document.getElementById('myDiv').style.width;/* this
        is cycle reference, but maybe only between COM and COM objects?
        And do not make leaks? */
    }
    styleLeaks();
    </script>
</body>
</html>

我是否理解主要思想?最后一个问题,Chrome 有一个任务管理器,当我从http://www.javascriptkit.com/javatutors/closuresleak/index.shtml使用它时,Windows 任务管理器会在每次刷新时显示内存使用量跳跃约 1mb :

function LeakMemory(){
    for(i = 0; i < 50000; i++){
        var parentDiv = 
        document.createElement("div");
    }
}

Chrome(21) 泄漏?我认为这不正常。所以我对 JS 垃圾回收的工作原理越来越感到困惑。

4

0 回答 0