Matt Kruse wrote:[color=blue]
> I'm aware of the circular reference memory leak problem with IE/closures.
> I'm not sure exactly how to resolve it in this situation. Also, Firefox
> appears to grow its memory size with the same code. So I'm wondering if I'm
> missing something?
>
> My test code is as follows:
>
> function myObj() {
> var req = new Object();
> req.temp = 0;
> if (window.XMLHttpRequest) { req.xmlHttpRequest = new XMLHttpRequest(); }
> else if (window.ActiveXObject) { req.xmlHttpRequest = new
> ActiveXObject("Msxml2.XMLHTTP"); }
> req.xmlHttpRequest.onreadystatechange =
> function() {
> if (req.readyState==4) {
> req.temp = req.xmlHttpRequest.responseText;
> }
> };
> req.xmlHttpRequest.open("GET","/",true);
> req.xmlHttpRequest.send(null);
> return req;
> }
> // Create a whole bunch of these objects to check for memory leak
> for (var i=0; i<1000; i++) {
> var x = new myObj();
> }
>
> What is the best way to avoid memory leaking in this example?
>
> --
> Matt Kruse
>
http://www.JavascriptToolbox.com[/color]
Not sure if this will solve your problem, but I noticed a few wasted
resources and unclear code.
First, when you say:[color=blue]
> function myObj() {
> var req = new Object();[/color]
You are actually instantiating two objects for every call to new myObj.
Second:[color=blue]
> req.xmlHttpRequest.onreadystatechange =
> function() {
> if (req.readyState==4) {
> req.temp = req.xmlHttpRequest.responseText;
> }
> };[/color]
For everything within the anonymous function, req should be 'this'.
This is how I would I would rewrite this:
function makeXMLRequest( URI ) {
var x = (
window.XMLHttpRequest ?
( new XMLHttpRequest() )
: ( new ActiveXObject( 'Msxml2.XMLHTTP' ) )
);
x.open( 'GET', encodeURI( URI || 'about
:blank' ), true );
x.send( null );
return x;
}
Now a call to x = makeXMLRequest (NOT new makeXMLRequest) will return
an instance of either XMLHttpRequest OR a new ActiveXObject of type
'Msxml2.XMLHTTP'.
This should result in more efficient garbage collection as well.
The real problem (I think) is that you are creating all of these
objects and not necessarily giving them time to complete the HTTP
request. This is probably preventing the necessary garbage collection
and creating 1000 simultaneous HTTP requests. Ouch.
Hope that helps.