开发者

Why does this code cause a memory leak in JavaScript?

开发者 https://www.devze.com 2023-04-13 06:33 出处:网络
<!doctype html> <head> <script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js\"></script>
    <!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();
        app开发者_开发技巧endMapMarker1();
    };

    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>

Both appendMapMarker1 and appendMapMarker2 will cause a memory leak, but appendMapMarker2 is much better than appendMapMarker1.

Can you tell me why this code causes a memory leak and why appendMapMarker2 is better than appendMapMarker1?


Your memory leak is quite obvious. You put an "infinite" number of elements in your frame.divs array. So reset the frame.divs array each time you call the appendMapMaker* function. Basically like this:

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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号