开发者

garbage collection of jquery.html

i was wondering if the following code would cause 开发者_开发技巧some problems like memory leak

<html>
<head>
    <script type='text/javascript' src='jquery-1.4.2.js'> </script>
    <script type="text/javascript">
        function a(){
            for(var i = 0; i < 50000; i++){
                $("#d").html("<span>" + i + "</span>");
            }
        }

    </script>
</head>
<body onload='a();'>
    <div id="d"></div>
</body>


A simple span is being created here in each iteration. The html() function in jQuery runs an internal cleanData function that removes associated data and events from all contained nodes which isn't the case here anyways.

Then jQuery sets the innerHTML property to the passed in string which frees the existing elements. It's up to the browser's garbage collector to reclaim that memory whenever it can. There are no leaks in this code at all. Chrome is actually very fast in releasing that memory. I see a drop off from 2.421MB to 748KB mainly from the span elements being released in under 3 seconds.

It does not wait for the page to unload to release this memory. These three snapshots were spaced apart by less than a second in which time almost 26000 HTMLElement objects were released from memory.

Before opening the page

garbage collection of jquery.html

After opening page (23000 HTMLElement objects had already been released immediately, around 27000 were remaining)

garbage collection of jquery.html

Less than a second later (all 27000 objects except 1 were released)

garbage collection of jquery.html


It will use memory (possibly on the order of a megabyte or 2) but it will not leak it.

When the page is closed the memory should be restored.

My results on a Dirty instance of Firefox:

                        Memory used (allow several seconds to settle)
                       -----------------------------------------------
Before opening page:        163,332K
Open and page finished:     164,932K  (temporarily spiked to about 210M)
After page closed:          163,668K

Note that the slight difference could be one of the many other tabs open, or it could be memory leaks that Firefox is famous for, but it is probably not that JS code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜