为什么此代码会导致JavaScript中的内存泄漏?

时间:2011-10-13 12:56:22

标签: javascript memory-leaks

    <!doctype html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script>
    function Frame(){
        this.divs=[];
        this.extra = new Array(2000);
    }

    Frame.prototype.reloadMapMarker = function(){
        //appendMapMarker2();
        appendMapMarker1();
    };

    function divClick(){

    }

    //a big surprise!!!
    function appendMapMarker1(){
        var div = document.getElementById('test');
        $(div).empty();
        var frag=document.createDocumentFragment();
        for(var i=0; i<100; i++){
            var newDiv=document.createElement('div');
            newDiv.onclick = divClick;
            newDiv.innerHTML = String(i);
            frag.appendChild(newDiv);
            frame.divs.push(newDiv);
        }
        div.appendChild(frag);
    }

    //less memory leak
    function appendMapMarker2(){
        var div = document.getElementById('test');
        var str = [];
        for(var i=0; i<100; i++){
            str.push('<div onclick="divClick()" style="margin:2px;border:1px solid #eee;">',i,'</div>');
            frame.divs.push(div.children[div.children.length-1]);
        }
        div.innerHTML = str.join('');
    }

    var frame =new Frame();
    window.onload=function(){
        setInterval(frame.reloadMapMarker,100);
    };
    </script>
</head>
<body>
    <div id="test"></div>
</body>

appendMapMarker1和appendMapMarker2都会导致内存泄漏, 但是appendMapMarker2比appendMapMarker1要好得多。

你能告诉我为什么这段代码会导致内存泄漏以及为什么appendMapMarker2比appendMapMarker1更好?

1 个答案:

答案 0 :(得分:1)

你的内存泄漏非常明显。您在frame.divs数组中放置了“无限”数量的元素。因此,每次调用appendMapMaker *函数时重置frame.divs数组。基本上是这样的:

function appendMapMarker*() {
    frame.divs = [];
    // ....
}