user415726
user415726

Reputation: 159

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>

Upvotes: 2

Views: 1603

Answers (2)

Anurag
Anurag

Reputation: 141879

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

alt text

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

alt text

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

alt text

Upvotes: 3

Brock Adams
Brock Adams

Reputation: 93483

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.

Upvotes: 1

Related Questions