Memory leak involving jQuery Ajax requests

后端 未结 3 2048
攒了一身酷
攒了一身酷 2020-12-18 04:21

I have a webpage that\'s leaking memory in both IE8 and Firefox; the memory usage displayed in the Windows Process Explorer just keeps growing over time.

The followi

相关标签:
3条回答
  • 2020-12-18 04:38

    I'm not sure about the leak, but your resetTable() function is very inefficient. Try fixing those problems first and see where you end up.

    • Don't append to the DOM in a loop. If you must do DOM manipulation, then append to a document fragment, and then move that fragment to the DOM.
    • But innerHTML is faster than DOM manipulation anyway, so use that if you can.
    • Store jQuery sets into local variables - no need to re-run the selector every time.
    • Also store repeated references in a local variable.
    • When iterating over a collection of any sort, store the length in a local variable, too.

    New code:

    <html> <head>
        <title>Test Page</title>
        <script type="text/javascript"
         src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
    </head> <body>
    <script type="text/javascript">
    $(function()
    {
        var $tbody = $("#content tbody");
    
        function kickoff() {
            $.getJSON("test.php", resetTable);
        }
    
        function resetTable(rows)
        {
            var html = ''
              , i = 0
              , l = rows.length
              , row;
            for ( ; i < l; i++ )
            {
                row = rows[i];
                html += "<tr>"
                    + "<td>" + row.mpe_name + "</td>"
                    + "<td>" + row.bin + "</td>"
                    + "<td>" + row.request_time + "</td>"
                    + "<td>" + row.filtered_delta + "</td>"
                    + "<td>" + row.failed_delta + "</td>"
                + "</tr>";
            }
            $tbody.html( html );
            setTimeout(kickoff, 2000);
        }
    
        kickoff();
    });
    </script>
    <table id="content" border="1" style="width:100% ; text-align:center">
    <thead>
        <th>MPE</th> <th>Bin</th> <th>When</th> <th>Filtered</th> <th>Failed</th>
    </thead>
    <tbody></tbody>
    </table>
    </body> </html>
    

    References:

    • jQuery Peformance Rules
    • Speed Up Your Javascript
    0 讨论(0)
  • 2020-12-18 04:56

    Please correct me if I'm wrong here but doesn't SetTimeout(fn) prevents the release of the caller's memory space? So that all variables/memory allocated during the resetTable(rows) method would remain allocated until the loop finished?

    If that's the case, pushing string construction and appendTo logic to a different method may be a little better since those objects would get freed up after each calling and only the memory of the returned value (in this case either the string markup or nothing if the new method did the appendTo()) would remain in memory.

    In essence:

    Initial Call to kickoff

    -> Calls resetTable()

    -> -> SetTimeout Calls kickoff again

    -> -> -> Calls resetTable() again

    -> -> -> -> Continue until Infinite

    If the code never truly resolves, the tree would continue to grow.

    An alternative way of freeing up some memory based on this would be like the below code:

    function resetTable(rows) {
        appendRows(rows);
        setTimeout(kickoff, 2000);
    }
    function appendRows(rows)
    {
        var rowMarkup = '';
        var length = rows.length
        var row;
    
        for (i = 0; i < length; i++)
        {
            row = rows[i];
            rowMarkup += "<tr>"
                    + "<td>" + row.mpe_name + "</td>"
                    + "<td>" + row.bin + "</td>"
                    + "<td>" + row.request_time + "</td>"
                    + "<td>" + row.filtered_delta + "</td>"
                    + "<td>" + row.failed_delta + "</td>"
                    + "</tr>";      
        }
    
        $("#content tbody").html(rowMarkup);
    }
    

    This will append the markup to your tbody and then finish that part of the stack. I am pretty sure that each iteration of "rows" will still remain in memory; however, the markup string and such should free up eventually.

    Again...it's been a while since I've looked at SetTimeout at this low level so I could be completely wrong here. In anycase, this won't remove the leak and only possibly decrease the rate of growth. It depends on how the garbage collector of the JavaScript engines in use deal with SetTimeout loops like you have here.

    0 讨论(0)
  • 2020-12-18 05:00

    I'm not sure why firefox isn't happy w/ this but I can say from experience that in IE6/7/8 you must set innerHTML = ""; on the object you want removed from the DOM. (if you created this DOM element dynamically that is)

    $("#content tbody").empty(); might not be releasing these dynamically generated DOM elements.

    Instead try something like the below (this is a jQuery plugin I wrote to solve the issue).

    jQuery.fn.removefromdom = function(s) {
        if (!this) return;
    
        var bin = $("#IELeakGarbageBin");
    
        if (!bin.get(0)) {
            bin = $("<div id='IELeakGarbageBin'></div>");
            $("body").append(bin);
        }
    
        $(this).children().each(
                function() {
                    bin.append(this);
                    document.getElementById("IELeakGarbageBin").innerHTML = "";
                }
        );
    
        this.remove();
    
        bin.append(this);
        document.getElementById("IELeakGarbageBin").innerHTML = "";
    };
    

    You would call this like so: $("#content").removefromdom();

    The only issue here is that you need to re-create your table each time you want to build it.

    Also, if this does solve your issue in IE you can read more about this in a blog post that I wrote earlier this year when I came across the same problem.

    Edit I updated the plugin above to be 95% JavaScript free now so it's using more jQuery than the previous version. You will still notice that I have to use innerHTML because the jQuery function html(""); doesn't act the same for IE6/7/8

    0 讨论(0)
提交回复
热议问题