473,721 Members | 1,818 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Closures + XMLHttpRequest + Memory Leak

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.XMLHttp Request) { req.xmlHttpRequ est = new XMLHttpRequest( ); }
else if (window.ActiveX Object) { req.xmlHttpRequ est = new
ActiveXObject(" Msxml2.XMLHTTP" ); }
req.xmlHttpRequ est.onreadystat echange =
function() {
if (req.readyState ==4) {
req.temp = req.xmlHttpRequ est.responseTex t;
}
};
req.xmlHttpRequ est.open("GET", "/",true);
req.xmlHttpRequ est.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
Jul 23 '05 #1
10 14089
Matt Kruse wrote:
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.XMLHttp Request) { req.xmlHttpRequ est = new XMLHttpRequest( ); }
else if (window.ActiveX Object) { req.xmlHttpRequ est = new
ActiveXObject(" Msxml2.XMLHTTP" ); }
req.xmlHttpRequ est.onreadystat echange =
function() {
if (req.readyState ==4) {
req.temp = req.xmlHttpRequ est.responseTex t;
}
};
req.xmlHttpRequ est.open("GET", "/",true);
req.xmlHttpRequ est.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

Not sure if this will solve your problem, but I noticed a few wasted
resources and unclear code.

First, when you say: function myObj() {
var req = new Object();
You are actually instantiating two objects for every call to new myObj.

Second: req.xmlHttpRequ est.onreadystat echange =
function() {
if (req.readyState ==4) {
req.temp = req.xmlHttpRequ est.responseTex t;
}
};


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.XMLHttpR equest ?
( 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.

Jul 23 '05 #2
Random wrote:
First, when you say:
function myObj() {
var req = new Object(); You are actually instantiating two objects for every call to new
myObj.


This is a simplified example of my real case, which needs to do this. But
that's unrelated...
This is how I would I would rewrite this:
Well, that doesn't something entirely different. You can't really solve a
problem by rewriting it and removing functionality, can you? :)
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.


Well that's because you've removed the handling function completely!

--
Matt Kruse
http://www.JavascriptToolbox.com
Jul 23 '05 #3
Matt Kruse wrote:
if (req.readyState ==4) {


Oops, this is actually:

if (req.xmlHttpReq uest.readyState ==4) {

of course :)

--
Matt Kruse
http://www.JavascriptToolbox.com
Jul 23 '05 #4
Matt Kruse wrote:
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? <snip> function myObj() {
var req = new Object();
req.temp = 0;
if (window.XMLHttp Request) { req.xmlHttpRequ est = new
XMLHttpRequest( ); } else if (window.ActiveX Object) {
req.xmlHttpRequ est = new ActiveXObject(" Msxml2.XMLHTTP" ); }
req.xmlHttpRequ est.onreadystat echange =
function() {
if (req.readyState ==4) {
req.temp = req.xmlHttpRequ est.responseTex t;
req.xmlHttpRequ est.onreadystat echange = null;

- At this point will remove the curricular reference and free the
closure.
}
};
req.xmlHttpRequ est.open("GET", "/",true);
req.xmlHttpRequ est.send(null);
return req;
} <snip> What is the best way to avoid memory leaking in this example?


Belt and braces would have you nulling the reference to the
XMLHttpRequest object once it is finished with.

Richard.
Jul 23 '05 #5
Richard Cornford wrote:
<snip>
- At this point will remove the curricular reference ...

<snip> ^^^^^^^^^^

That should have been 'circular'.

Richard.
Jul 23 '05 #6
Richard Cornford wrote:
req.xmlHttpRequ est.onreadystat echange = null;
- At this point will remove the curricular reference and free the
closure.


That's what I thought too, but no luck. IE says "type mismatch".

Instead, I found that this appears to work:

delete req.xmlHttpRequ est['onreadystatech ange'];

And in fact, I'm doing this just to be safe:

delete req.xmlHttpRequ est['onreadystatech ange'];
req.xmlHttpRequ est = null;
req = null;
CollectGarbage( );

That *appears* to work in IE. I can see the memory usage grow to over 150MB,
then drop back to 30MB, so I assume the leak is gone. However, I don't know
of any way to test for sure. Do you?

--
Matt Kruse
http://www.JavascriptToolbox.com
Jul 23 '05 #7
Matt Kruse wrote:
Random wrote:
First, when you say:
function myObj() {
var req = new Object(); You are actually instantiating two objects for every call to new
myObj.


This is a simplified example of my real case, which needs to do this. But
that's unrelated...


Clearly I misunderstood. Sorry I didn't catch that based on your
original post.
This is how I would I would rewrite this:


Well, that doesn't something entirely different. You can't really solve a
problem by rewriting it and removing functionality, can you? :)


See above.
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.


Well that's because you've removed the handling function completely!


See above.

Jul 23 '05 #8
Matt Kruse wrote:
Richard Cornford wrote:
req.xmlHttpRequ est.onreadystat echange = null;
- At this point will remove the curricular reference and
free the closure.
That's what I thought too, but no luck. IE says
"type mismatch".


Yes, you are right. It looks like I went for assigning a reference to a
small harmless (and not 'inner') function to clear the closure in my
version.

<snip> And in fact, I'm doing this just to be safe:

delete req.xmlHttpRequ est['onreadystatech ange'];
req.xmlHttpRequ est = null;
req = null;
CollectGarbage( );

<snip>

Calling CollectGarbage without verifying its existence will result in
errors on browsers that do not support it.

Richard.
Jul 23 '05 #9
i ussing xmlhttprequest for few years. Typicaly i use sinchronus data
trander

example of my uses

senddata(method ,data,debug,url )
debug = shows respondense content

myResult = sendData('updat e',{id:1,name:3 4});

after this call i get myResult javascript array (or string)

for asyncronus can be added callback function

Jul 23 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
5555
by: Mark D. Anderson | last post by:
About a month ago Richard Cornford did an interesting analysis of a memory leak in jscript (internet explorer) when there are "circular" references between DOM objects and (real) jscript objects: http://groups.google.com/groups?selm=bcq6fn%24g53%241%248300dec7%40news.demon.co.uk This message summarizes some testing I've done and their results. These results somewhat contradict Cornford's conclusions; I haven't
2
1778
by: Robert | last post by:
Hi, Do I understand correctly from http://jibbering.com/faq/faq_notes/closures.html that the following will create a memory leak in IE? function createMemoryLeak(id) { var el = document.getElementById(id);
1
1232
by: Cylix | last post by:
I have read an article about the memory leak issue on nowadays website, "Circular References-When mutual references are counted between Internet Explorer's COM infrastructure and any scripting engine, objects can leak memory. This is the broadest pattern." Anyone can explain this for me? How would be the coding make circular reference?
2
2370
by: Robert | last post by:
Hello javascript group readers, I have a question regarding how to prevent memory leaks in Internet Explorer when using closures. I already knew about the circular reference problem, and until now was able to prevent memory leak problems. But I needed to store DOM elements and can't solve it anymore. So I search the group archive to see if I missed any valuable information. I found some interesting articles, but somehow could not apply...
2
4751
by: m0nkeymafia | last post by:
I have spent the past few weeks trying to figure a way around this problem, and have yet to find a good enough solution. Internet Explorer leaks memory when I update a div container using innerHTML, this does not occur in firefox. This would not be a problem except the webpage is required to be left on for weeks on end without being restarted. I presume the issue with innerHTML is that Internet Explorer apparently parses what you give...
2
2698
by: Jay | last post by:
I have a web app running on the windows CE device. In one of the asp.net pages - it has javascript code. That seems to have a memory leak. When I run the web app - in about one hour, the app hangs. I looked at the memory and it seems to be full. I removed all the javascript code - and the app seems to be have no leaks. As soon as I include my javascript code - the memory consumption gradually increases. Whether I actually invoke the...
10
2589
rizwan6feb
by: rizwan6feb | last post by:
I am working on an ajax chat application, done most of the work but when i tested it on IE (both on IE6 and IE7), found that there is a memory leak. The application works fine on FF. How can i fix this? I have used ajax in the following way (this is a similar to how i am using ajax in my chat application); incrementer.php file on line # 34 simply prints an incremented value from the session <html> <head> <script language="javascript">...
18
2145
by: Daniel Orner | last post by:
Hi all, I've been trying to pin down a memory leak in IE6 for several WEEKS now. I've done my share of googling etc., and know all about common leaks like circular references and closures, but have found nothing like this. This app is designed to run in a kiosk environment, so it has things like a persistent frame which holds data as well as the visible frame (actually an iframe). After 1,000 page transitions our app is up by almost...
0
8838
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8728
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9366
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9130
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8005
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5979
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4751
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3188
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2130
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.