0
    <!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>

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?

1 Answer 1

1

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 = [];
    // ....
}
Sign up to request clarification or add additional context in comments.

4 Comments

i dont think so,if you are right,appendMapMarker2 is the same as appendMapmarker1 on memory cost.but appendMapMarker1 will consume memory at the speed of 8M/s.
and appendMapMarker2 is 20K/s
I am right. I just run the modified appendMapMarker1 method for minute: no memory leak. The reason why appendMapMarker2 isn't leaking is that you have an exception in it, which causes that no elements are added to the frame.divs array.
so if we reset frame.divs, there is no memory leak in this code?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.