473,703 Members | 2,328 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Aync XMLHTTP with Javascript: memory problems

Currently I'm doing some experimenting with the XMLHTTP object in
Javascript. Now,
the XMLHttp object is asynchronous (at least in this case), and the
following code causes a significant memory loss even though I seem to be
allocaitng everything; help would be *vastly* appreciated. What am I doing
wrong here? I thought I was doing everything correctly (setting things to
null, for example) but none of the memory seems to get replaced. I've been
experiencing allocations of memory up to 125 megabytes (!) that simply
persist in the browser, never to go away...

Thanks in advance for any help you can provide!

ASyncQueue = new Array();
-Justice
function DataHandlerLook upLoop(value, id, numberOfLoops)

{

for (var loopCount = 0; loopCount < numberOfLoops; loopCount++)

{

DataHandlerLook up(loopCount,lo opCount,id);

}

}

function DataHandlerLook up(value, number, id)

{

++asyncsRunning ;

AsyncQueue.push (new Object());

AsyncQueue[number].ThisElement = document.getEle mentById(id);

AsyncQueue[number].Server = new ActiveXObject(" Msxml2.XMLHTTP" );

AsyncQueue[number].Server.onready statechange = f;

AsyncQueue[number].Server.open("G ET",
"http://localhost/MyCompany/data.metadata?t ext=" + value, true);

AsyncQueue[number].Server.send(va lue);

}

function f()

{

var temporaryLength = AsyncQueue.leng th;

for (var index = 0; index < AsyncQueue.leng th; ++index)

{

if (AsyncQueue[index] != null)

{

if (AsyncQueue[index].Server.readySt ate == FINISHED)

{

AsyncQueue[index].Server.abort() ;

AsyncQueue[index].Server = null;

delete AsyncQueue[index].Server;

AsyncQueue[index].ThisElement = null;

delete AsyncQueue[index].ThisElement;

AsyncQueue[index] = null;

--asyncsRunning;

}

if (asyncsRunning == 0)

{

var tempQueueLength = AsyncQueue.leng th;

for (var ix = 0; ix < tempQueueLength ; ++ix)

{

AsyncQueue.pop( );

}

CollectGarbage( );

}

}

Jul 20 '05 #1
5 6084
On Fri, 28 Nov 2003 03:47:14 GMT, "Justice" <ju**********@h otmail.com>
wrote:
Currently I'm doing some experimenting with the XMLHTTP object in
Javascript. Now,
the XMLHttp object is asynchronous (at least in this case), and the
following code causes a significant memory loss even though I seem to be
allocaitng everything; help would be *vastly* appreciated. What am I doing
wrong here? I thought I was doing everything correctly (setting things to
null, for example) but none of the memory seems to get replaced. I've been
experiencing allocations of memory up to 125 megabytes (!) that simply
persist in the browser, never to go away...
<snip />

Been there, done that.
AsyncQueue[index].Server.abort() ;

AsyncQueue[index].Server = null;

delete AsyncQueue[index].Server;

AsyncQueue[index].ThisElement = null;

delete AsyncQueue[index].ThisElement;

AsyncQueue[index] = null; You don't need to call abort() or any of the 4 lines after that.
CollectGarbage( );

CollectGarbage won't solve your problems. It is only useful in
debugging as it forces the garbage collector to run at a known point.

Aside from executing code too many times (the f() function is called 3
times per HTTP request and you loop through each item in your array),
there doesn't appear to be any problems noticable at first glance.
But this isn't your actual code, is it? It doesn't make much sense to
make HTTP requests but do nothing with the results....

Regards,
Steve
Jul 20 '05 #2

"Steve van Dongen" <st*****@hotmai l.com> wrote in message
news:uk******** *************** *********@4ax.c om...
Been there, done that.
AsyncQueue[index].Server.abort() ;

AsyncQueue[index].Server = null;

delete AsyncQueue[index].Server;

AsyncQueue[index].ThisElement = null;

delete AsyncQueue[index].ThisElement;

AsyncQueue[index] = null; You don't need to call abort() or any of the 4 lines after that.

CollectGarbage( );

CollectGarbage won't solve your problems. It is only useful in
debugging as it forces the garbage collector to run at a known point.


I simply threw it in to see if memory was actually being deallocated.
Unfortunately, nothing really changed.
Aside from executing code too many times (the f() function is called 3
times per HTTP request and you loop through each item in your array),
How can I necessarily avoid calling f three times, however? Attaching f to
onreadystatecha nge basically guarantees that this thing is going to get
called every time.

Ideally, I would have liked a way in "f" to determine which server object
fired the onreadystatecha nge event, but no information comes back from
onreadystatecha nge to indicate this, hence my convoluted attempts at
resolving things.
there doesn't appear to be any problems noticable at first glance.
But this isn't your actual code, is it? It doesn't make much sense to
make HTTP requests but do nothing with the results....


You're correct. However, even this code (without anything notable in
function "f", which would do something w/ the results) leads to memory
leaks. If I simulate an environment where, say, 400 of these requests are
made, the memory piles up and piles up and eventually I have IE using 156
megabytes of memory.

Unfortunately, although there don't *seem* to be any problems noticeable
(that's what I thought too, other than some semi-inefficient ways of going
through the asynclist) the memory allocations for this are enormous when 200
or so requests go through.

Thanks for any insight you can provide,
-Justice
Jul 20 '05 #3
On Sun, 30 Nov 2003 05:09:09 GMT, "Justice" <ju**********@h otmail.com>
wrote:

"Steve van Dongen" <st*****@hotmai l.com> wrote in message
news:uk******* *************** **********@4ax. com...
Been there, done that.
> AsyncQueue[index].Server.abort() ;
>
> AsyncQueue[index].Server = null;
>
> delete AsyncQueue[index].Server;
>
> AsyncQueue[index].ThisElement = null;
>
> delete AsyncQueue[index].ThisElement;
>
> AsyncQueue[index] = null;

You don't need to call abort() or any of the 4 lines after that.
It looks like you may actually need to set .Server and .ThisElement =
null though frankly I'm not sure why.
> CollectGarbage( );

CollectGarbage won't solve your problems. It is only useful in
debugging as it forces the garbage collector to run at a known point.


I simply threw it in to see if memory was actually being deallocated.
Unfortunatel y, nothing really changed.
Aside from executing code too many times (the f() function is called 3
times per HTTP request and you loop through each item in your array),


How can I necessarily avoid calling f three times, however? Attaching f to
onreadystatech ange basically guarantees that this thing is going to get
called every time.

Ideally, I would have liked a way in "f" to determine which server object
fired the onreadystatecha nge event, but no information comes back from
onreadystatech ange to indicate this, hence my convoluted attempts at
resolving things.


See below.
there doesn't appear to be any problems noticable at first glance.
But this isn't your actual code, is it? It doesn't make much sense to
make HTTP requests but do nothing with the results....


You're correct. However, even this code (without anything notable in
function "f", which would do something w/ the results) leads to memory
leaks. If I simulate an environment where, say, 400 of these requests are
made, the memory piles up and piles up and eventually I have IE using 156
megabytes of memory.

Unfortunatel y, although there don't *seem* to be any problems noticeable
(that's what I thought too, other than some semi-inefficient ways of going
through the asynclist) the memory allocations for this are enormous when 200
or so requests go through.


Whenever you use nested functions, a closure is created, giving the
enclosed function access to all of the outer function's arguments and
local variables. This is a common source of memory leaks. The
problem comes down to how relatively easy it is to create circular
references when you don't realize what is really going on. The
JScript garbage collector is capable of breaking circular references
between any number of JScript objects, but it cannot break a circular
reference where the chain includes an external object like an element
in IE or a COM object.

So, the point is basically, try not to mix nested functions and DHTML
and/or ActiveX because you might end up with a circular reference that
cannot be broken and, therefore, a memory leak.

This is an example of a function that leaks memory...
function omicron()
{
var x = MakeNewDiv();
x.foo = epsilon;
function epsilon()
{
...
}
}
The circular reference is:
x --> div --> epsilon --> x

That said, the only way to pass data to your onreadystatecha nge
handler is to use a closure. This example doesn't leak...

AsyncQueue = new Array();
asyncsRunning = 0;

function Init()
{
for (var i=0; i<500; i++)
{
AsyncRequestSta rt("", "id" + i);
}
}

function AsyncRequestSta rt(value, id)
{
var index;
var requestInfo = new Object();

index = AsyncQueue.leng th;
AsyncQueue.push (requestInfo);

// requestInfo.Thi sElement = document.getEle mentById(id);
requestInfo.Ser ver = new ActiveXObject(" Msxml2.XMLHTTP" );
requestInfo.Ser ver.onreadystat echange = function () {
AsyncRequestCom plete(index);
};
requestInfo.Ser ver.open("GET",
"http://localhost/MyCompany/data.metadata?t ext=" + value, true);
requestInfo.Ser ver.send(value) ;
asyncsRunning++ ;
}

function AsyncRequestCom plete(index)
{
var requestInfo = AsyncQueue[index];
Log(index + ": readyState=" + requestInfo.Ser ver.readyState) ;
if (requestInfo.Se rver.readyState == 4 /*FINISHED*/)
{
asyncsRunning--;
UpdateStatus();

// requestInfo.Thi sElement = null;
requestInfo.Ser ver = null;
delete AsyncQueue[index];
}
requestInfo = null;
}

function Log(s)
{
window.status = s;
}

function UpdateStatus()
{
document.body.i nnerText = "Pending Requests: "
+ asyncsRunning;
}

Regards,
Steve
--
Please post questions to the newsgroup; everyone benefits.
This post is provided "AS IS" with no warranties, and confers no rights
Sample code subject to http://www.microsoft.com/info/cpyright.htm
Jul 20 '05 #4

"Steve van Dongen [MSFT]" <st*****@online .microsoft.com> wrote in message
news:33******** *************** *********@4ax.c om...
It looks like you may actually need to set .Server and .ThisElement =
null though frankly I'm not sure why.
I thought I had read something about references to the DOM causing leaks in
other's applications. (Part of it is just my paranoia in Javascriptabout
setting everything to null once I am done with the objects).

[explanation of closures and circular references]
See, I figured that *might* have been the problem and thus rearchitected
things to pull "f" out of the closure. However, that still didn't do
anything in terms of the memory usage. (see below where I reply to your
example)
That said, the only way to pass data to your onreadystatecha nge
handler is to use a closure. This example doesn't leak...


Thanks for your example! However, running your example through tresting and
looking at IE's memoery usage before and after:
IE before Init() is called:

Physical Memory: 14944 K
Peak Memory Usage: 14,944 K
Virtual Memory: 6,640 K

IE after Init() finishes:
Physical Memory: 23,880 K
Peak Memory Usage: 25,472 K
Virtual Memory: 16,872 K

And, just for kicks, I jacked up your Init function to loop 4,000 times
instead of just 500. Here were my results after it finished:

Physical Memory: 66,830 K
Peak Memory Usage: 92,104 K
Virtual Memory Usage: 73,104 K

This memory usage does not go away until I close IE (it stays even when
navigating to other sites). This is the memory leak I am referring to,
which now you have caught as well!

Therein lies my problem...?

Thanks,

-Justice
Jul 20 '05 #5
On Sun, 30 Nov 2003 18:20:15 GMT, "Justice" <ju**********@h otmail.com>
wrote:

"Steve van Dongen [MSFT]" <st*****@online .microsoft.com> wrote in message
news:33******* *************** **********@4ax. com...
That said, the only way to pass data to your onreadystatecha nge
handler is to use a closure. This example doesn't leak...


Thanks for your example! However, running your example through tresting and
looking at IE's memoery usage before and after:
IE before Init() is called:

Physical Memory: 14944 K
Peak Memory Usage: 14,944 K
Virtual Memory: 6,640 K

IE after Init() finishes:
Physical Memory: 23,880 K
Peak Memory Usage: 25,472 K
Virtual Memory: 16,872 K

And, just for kicks, I jacked up your Init function to loop 4,000 times
instead of just 500. Here were my results after it finished:

Physical Memory: 66,830 K
Peak Memory Usage: 92,104 K
Virtual Memory Usage: 73,104 K

This memory usage does not go away until I close IE (it stays even when
navigating to other sites). This is the memory leak I am referring to,
which now you have caught as well!


Sounds like you're measuring at different states. Before Init() is
called there are 0 pending requests; when Init() is complete there are
500 (or 4000) pending requests. You have to measure when the pending
request count reaches 0 again.

When I was testing my code I found that when I refreshed the page the
memory usage before and after was pretty consistent. Adding
CollectGarbage( ) at the end made it a little more consistent which is
what I'd expect. Another thing I noticed was that on the first run
memory usage after all the requests had completed was higher than at
the beginning. I suspect the discrepancy is the result of IE delay
loading some libraries and not indicative of a memory leak caused by
the script.

Regards,
Steve
--
Please post questions to the newsgroup; everyone benefits.
This posting is provided "AS IS" with no warranties, and confers no rights.
Sample code subject to http://www.microsoft.com/info/cpyright.htm
Jul 20 '05 #6

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

Similar topics

3
3090
by: Mark | last post by:
Hi all i was just wondering if you help. I have to send a cgi request to a company using xmlhttp request. They reply back with a line of info but when you view the internet explorer source code you see the XML format. I was just wonder if anyone could help me save the xml format to a xml file. I woul like to show you my code but there is to much confidential information about the company.
7
2501
by: Fabri | last post by:
I'm trying to develop a way to include static files in htm pages with javascript. I'm trying to use XMLHTTP object this way: ---------------------------------------------------------------------- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head>
9
5575
by: fochie | last post by:
Greetings, I'm having a problem when I try to GET a file from my server via xmlhttp when using Mozilla. With IE I can get any type of file fine, get/display headers fine, etc. With Mozilla, using the same HTML/JS it always returns no data (xmlhttp.responseText is null). When I try to get headers using Mozilla or display the http status code I get some obscure exception in the javascript console that I've given up on searching for an...
5
3349
by: warteschlange | last post by:
i want to postload javscript from another javascript. This works fine in firefox and IE6 for macIE i can use an Iframe to load the code and inject it with insertAdjacentHTML The problems arise with safari and opera. both load the new code with XMLHttpRequest, but the code is no 'executable' To make this possible on IE i had to use the magic 'DEFER' attribute.
1
3099
by: mirandacascade | last post by:
I recognize that this question is not about javascript per se...it is more about xmlhttp...posting the question at this site because it appears as though this site has many posts related to xmlhttp Situation is this: 1) making use of the COM object MSXML2.XMLHTTP in a client application 2) I use the open() method of the COM object and specify a "POST", then I use the send() method of the COM object 3) when the url is an http url, able...
1
3850
by: wkerplunk | last post by:
Below is what I have build with several different languages. It works great but I need help, I am stuck. When you click on an item in the dropdown autocomplete div it does a mousedown function and send the item number to the xmlHttp and works awesome. Now I need to add an apply button next to it. so they can type in the complete number then hit apply and it does the same function. I cant get it to work with the script I have. The image...
4
8279
by: sirjohnofthewest | last post by:
If I possessed the power to sway the mind of every user in the world to delete all forms of Internet Explorer I would die a happy man. Hi guys, I frequently visit this site to get answers to my problems and this one is really getting to me... I have a page that allows you to Browse Authors. There are three drop down boxes that auto-populate via AJAX. I have a file which it calls and returns the dynamically built XML file in the boxes...
2
12468
by: trpost | last post by:
Is it possible to execute javascript as passed in xmlHttp.responseText Here is what I am doing: search.js var xmlHttp xmlHttp=GetXmlHttpObject() var url="search.php" xmlHttp.onreadystatechange=stateChanged
0
9251
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...
0
9122
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9017
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
8963
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7872
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...
1
6588
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5922
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();...
1
3125
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
2069
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.