开发者

How Can I Assist IE's Flawed Garbage Collector?

I have a JavaScript application that uses XMLHttpRequest to fetch and parse about 60,000 XML documents. However, IE's memory usage grows quickly, and eventually the program crashes. I suspect this has to do with IE's JScript GC. Below is a simplified version of my code:

Above the code, I declare two variables:

var xmlhttp;
var xmlDoc;

When the c开发者_开发问答ode first starts running, I set the value of xmlhttp:

xmlhttp = new XMLHttpRequest();

The script then enters the main loop:

function loadXML() {

    xmlhttp.abort(); 
    xmlhttp.open("GET", url, false);
    xmlhttp.setRequestHeader('Content-Type', 'text/xml', 'Pragma', 'no-cache');
    xmlhttp.send("");
    while (xmlhttp.readyState != 4) { }
    xmlDoc = xmlhttp.responseXML;
    setTimeout("readXML()",0);

}


function readXML() {

    //Reads the XML.
    //If all data has been retrieved, exit loop.
    //Else, change the url and go back to loadXML()

}

Google Chrome runs the code just fine, with no errors. However, IE loops about 2000 times before crashing with an "Out of Memory" error. Is the Garbage Collector not doing it;s job? Can I rewrite my code to prevent problems?


You should not use a busy loop at all to wait for the result of an XMLHttpRequest. Also, there's no reason to have the xmlhttp object public. Instead, create a new one on every call and register a callback:

function loadXML() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET", url, false);
    xmlhttp.setRequestHeader('Content-Type', 'text/xml', 'Pragma', 'no-cache');
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == 4) {
        xmlDoc = xmlhttp.responseXML;
        readXML();
      }
   };
   xmlhttp.send("");
}


You should definitely follow phihag's advice on a better way to process the xml requests and wait for their completion.

Then I would suggest nulling out your old xmlhttp object and creating a new one for each successive request so each old request can be entirely freed:

You don't show us how you go about running the same thing 60,000 times so I can't really help with the details of that code, but if the xmlhttp object itself is leaking some memory on each xmlhttp request, then throwing away the old object and creating a new one each time may help.

We also can't see what you're doing in readXML that could be leaking or what you're doing in the code that loops and gets the next request. You could be leaking function closures, you could have circular object references, etc...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜