I've seen lots of hair-pulling and confusion over memory management and garbage collection in Flex and Flash. Memory diagnostic tools are on the way, but until then, determining if you have a memory leak is a difficult thing to do. The attached presentation attempts to provide a simplified model of how the Flash Player manages memory. Hopefully, once you get a better understanding, it will save you time and hassle trying to detect memory leaks in your applications.
I also put together a sample app that has a straightforward memory leak that hopefully will serve as an example of how I diagose memory leaks in Flex 2x. The tools in the next release will make this much easier, but the technique used here has served me well.

Alex, I've got a pretty large application that has some serious memory leak issues. We're working with Adobe support as well as a consulting company called Ensemble, but we don't have any definitive answers yet.
I'm curious about how you would plug the memory leak in your sample application in hopes that we'll be able to plug ours as well.
------------------
In the sample given, the addEventListener causes the leak. I would either find a way to remove it or use a weak reference listener.
I have the same problem!!! I have a quite large application that uses a lot of popups...I hardly wait for the problem to be solved because until then the application it's almost useless.
------------------
I'm not sure what problem you are talking about. We'll have better diagnostic tools in the next release, but in general it still requires good coding on your part to eliminate memory leaks.
We're working on 2 huge Flex applications, memory leak is awfull, after hours of investigation it appears that many components, effects, transitions that can be found in Flex cause memory leak. The only way to get rid of them is to not use them.
In general we were enthousiasts starting working with Flex and now I don't know if we will do a project in Flex again.
Almost the complete Flex framework needs to be rewritten by developers with good software engineering knowledge.
Anyone who looks in detail in the source code of the Flex components will understand why I suggest this.
If Adobe does not rewrite Flex, Microsoft alternative (silverlight), which is planned for end of year will be adopted.
Too sad Adobe messed up Flex (and version 3 does not seem to correct all issues I'm talking about), considering the advance they had in Rich Internet Application.
--------------------------
Sorry to hear that you are disappointed. I'm certainly not going to claim we don't have memory leaks, but more often than not there is either a misunderstanding of the situation or a workaround. If you have specific examples, please let us know via the bug base at bugs.adobe.com/jira.
We greatly value the feedback and participation of users in order to improve our technology and stay ahead of the competition.
I have major problems with the image component. In a very simple project (like the photo viewer sample) I tried to change the image.source with binding to a dropdownlist. In internet Explorer the memory increases with every new image (even when the image was loaded before). Firefox is o.k. Even when I instanciate the image dynamically add it to a canvas and remove this child later from the canvas, the problem is still present. Is the image component not capable for displaying images dynamically? I can´t believe this.
--------------------
Because GC is opportunistic, you can get misleading results by looking at memory usage. IE has a different management scheme so it isn't suprising to get different results in FF. The only true test is to run through a sequence of images for hours and see if memory stabilizes at something reasonable.
Hi,
I just want to give you a feedback about the issue "IE doesn´t keep reserved memory". I tested the photo viewer sample Application from the flex 2.01 SDK. Memory increases above the physical memory within minutes (applications memory use was higher than 700 MB!). There seems to be no limit. I also tested it with the UILoader component - same issue and I guess that seems to be a major bug. In the past we created some flash based webapplications like the one you´ll find in the attached URL, which are running without problems. These appliactions rely heavily on loading images dynamically and we plan to migrate them to flex. Also we plan to migrate our flash based PDF-Proofreader to flex, but with this open issue I see no chance for us to do this. I`ll would be glad for any advice to solve the problem. I guess Adobe must be aware of such a huge memory hole...
-----------
Don't know. Please file a bug so we can track this issue. We have lots of folks developing sites full of images and haven't seen too many complaints yet. Make sure you have the hotfix version.
You don't have to go anywhere, simply open up the image browser example currently on adobe site, http://www.adobe.com/go/flex_photoviewer_app,
enter the slide show mode, and watch the ie memory increasing at 7MB every time a new image is loaded.
or use the following code to reproduce the memory issue:
private var imageArr:Array = [
"assets/testimage1.jpg",
"assets/testimage2.gif",
"assets/testimage3.jpg",
"assets/testimage4.png",
"assets/testimage5.jpg",
"assets/testimage6.gif",
"assets/testimage7.png"];
private var timer:Timer = new Timer(2000);
private function init():void
{
timer.addEventListener(TimerEvent.TIMER,changeImage);
timer.start();
}
private function changeImage (event:TimerEvent):void
{
image.source = imageArr.shift() as String;
}
]]>
---------
I'll try to find time to look into it. But please file a bug if you haven't.
Grant Skinner has an excellent articles on Flex / Flash memory leaks and also has some nice examples of a garbage collection class.
Check out his blog:
http://www.gskinner.com/blog/archives/2006/06/as3_resource_ma.html
Hi,
I am to start a quite huge application with the need of a RIA.
Till now, our choice is to use Flex on the client side. Are those memory leaks only appearing when using fancy graphical effects or not? Can anybody comment, please?
Thanks
---------------
I still have to look into this further. As far as I know, several folks have been building some very large projects w/o memory leak issues.
The thought of anyone saying that because of this issue, they would switch to using Silverlight is rather humerous. If you look at IE's history with regard to memory leaks you would realize that Microsoft is not immune for this kind of issue. Almost every technology that runs inside IE (Flash, Flex or Javascript) makes the leaks in IE known. Chances are though, that this is a Microsoft issue, not an Adobe issue.
Any update on when these tools will come out?
-------------
Memory leak and performance profilers are part of FlexBuilder 3, and Beta 2 just came out this week. It has a few glitches, but I have successfully used it to diagnose a few problems.
Regarding memory leaks and "IE doesn´t keep reserved memory"...
Try running Photo Viewer App in IE (http://www.adobe.com/go/flex_photoviewer_app).
Observe how memory usage increases for the IEXPLORE.EXE process.
Minimize IE.
Maximize (restore) IE.
Hey, where did all that allocated memory go...?!
We have had general memory issues when navigating from Flash-app (page) to a non-Flash HTML page and the back. Memory usage is increasing continously allthough the entire Flash Player is removed every other page. But only in IE. Not in Firefox.
Memory management in IE could be better.
/Christer
Isotop AB (www.isotop.se)
Sweden
Hi, searching for memory leaks with Flex Builder 3, Beta 2, in a strongly module based application, I found the following:
----------------
thanks
My flash application need a lot of memory to run. When the app run in IE with Flash9.ocx ActiveX, the System.totalmemory is always between 10M~20M. When the app run in FF/Opera with NPSWF32.dll Plugin, the totalmemory is between 100M~200M. The problem is that my app crashed constantly in IE with null pointer exception(exp code 0x00000005), but never crashed in FF/Opera. I think it is because the memory management between flash.ocx and npswf32.dll is different. Could you give me some advice? My app really need a lot of memory. I want IE's totalmemory can increse to 100M+.
-------------
Memory utilization does differ between browsers. The memory profiler can help you figure out what you can trim and when.
My tips based on empircal evidence:
a) Avoid the popup manager altogether for non-trivial popups (e.g. that have webservices, containers and controls in them). The memory is almost impossible to reclaim.
b) If you want to minimize memory management problems, avoid MXML. Use ActionScript instead. (Yes, you heard me right, avoid MXML.)
Coding in ActionScript is like driving stick shift. It's much much much harder, but results in a lighter weight, more performant engine.
MXML is much more intuitive, but doesn't work as well.
There is no MXML based example that a guy like Alex can't write with ActionScript in a more efficient way.
Perhaps the really brilliant programmers at Adobe like Alex don't realise it, but they rarely use mxml and I've noticed this culture to be quite pervasive in a lot of the Flex engineers. They're all still very ActionScript based. MXML strikes me as being not fully tested from a memory management perspective.
----------------
Well, I don't agree with all of your claims, but for sure, I can tune code in AS better than in MXML. That's the price you pay for declarative markup, but declarative markup has its advantages.
We want to fix memory leak issues so if you've got simple test cases, please file bugs.
-Alex
I had already noticed that running Flex in debug mode leaked memory when unloading modules.
I discovered that this memory leak was partly caused by the debug Flash Player ActiveX itself.
Depending on the module to unload, about 10% of the module unloading leak is caused by the debug Flash Player ActiveX, the other 90% being caused by the debug version of the module swf.
So, if you need to test a modular application for memory leaks, make sure to :
Doing this + all of the 7 points listed in my earlier post, lead to a completely stable and leak-free modular application : modules can be loaded and unloaded for ages without memory increase.
Actually, Is Adobe Flash GC depends on the sandbox (IE, FireFox, AIR) where flash is executed?
It's curious to notice that AIR GC works very very bad whereas IE flash plugin GC works better.
-----------------------
The GC algorithm is probably the same. What is different between player types is how many pages of memory get allocated and how big those pages are, and it is when those pages start to fill up that GC kicks in. If you have an example of debiliating GC in AIR, you should file a bug.
Just my 2cents to memory usage of mxml component compare to action script class (cf. Jackflit comment).
Until now I was not taking care of the amount of memory allocated by my flex app. But as I need to create a great number of visual components I was really surprised by the huge greediness of flash player.
A simple Label is more than 5Ko, a box container 3Ko.
My base component used for this test is an Image and a Label into a Hbox into a VBox.
I made first an mxml component extending a VBox.
Each instance of this component is using an average of 22 Ko.
(I made the test by creating blocks of 1000 objects)
Then I made exactly the same component by writing an action script class and create the same amount of instances. The memory allocation is around 16 Ko for each instance.
So mxml component need in this exemple 37% more memory than an as3 class.
We really pay the price !
-----------------
Yup, nothing in life is free. MXML is not as efficient as AS, but it makes it easier to code certian things. I'll have to see why a Label is eating 3K. That sounds kind of high.
Hi Alex,
I have a huge memory leak problem and it's probably a no-brainer, but I still don't understand what I'm doing wrong here.
I want to call a service regularly. My app is something like this:
mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" applicationComplete="createTimer()" layout="absolute">
mx:HTTPService resultFormat="xml" id="srvHTTP" url="http://example:7000/" result="handleResult(event)" fault="handleFault(event)"/>
mx:Script>
import mx.rpc.events.FaultEvent;
import mx.rpc.events.ResultEvent;
private var timer1:Timer;
private var xmlData:XML;
public function createTimer():void{
timer1=new Timer(10,0);
timer1.addEventListener(TimerEvent.TIMER,timerHandler);
timer1.start();
}
private function timerHandler(event:TimerEvent):void {
sendRequest();
}
private function handleResult(e:ResultEvent):void {}
private function handleFault(e:FaultEvent):void{}
private function sendRequest():void
{
xmlData=;
srvHTTP.send(xmlData);
}
]]>
--------------------
Alex responds:
I don't see anything wrong with your example, but you should use the memory profiler to analyze your leaks.
Hi,
I am new to to flash and flex.
I tried executing the simple FlickrRIA.mxml and FlickrThumbnail.mxml from Adobe's learn site. Basically a Tilelist is bound to flickr rss feed which displays some thumbnails
Even though the thumbnails are only 5k each and 20 are shown (so 100K) the increase in memory is about 4MB.
Similarly If i load a 1 MB local image instead of a 5K thumbnail the virtual memory in task manager shows 600 MB !!!
Any tweaks we need to do.
We are evaluating doing a large desktop application implementation in flash and hence want to be sure about memory issues.
------------------------
Alex responds:
We've seen the browsers be lazy about cleaning up memory. On IE, I can minimize and restore the browser window and it will flush most of that memory. We're still trying to figure out what we can do about that. Otherwise, use the profiler and see what it thinks is happening to memory. If that number is going up, then you should figure out why.
We are developing a very large, multiple document interface application in AIR with Flex 3. We have memory leaks all over the place from the framework and the internal player not releasing any memory. We have tried and tried to have our code clean up as best as it can but we still end up with Flash holding on to something, and that in turn causes other things to be held on to. Our application reaches over 600MB in allocated memory after opening AND CLOSING one of our larger files just 5 or 6 times!
If you want a really easy example of the horrible memory leaks in Flex 3 then just add a Menu to a AIR app, give it some data to show in the menu and then watch as it never releases its item renderer's memory back!
--------------------------
Alex responds:
I've heard that AIR has some GC issues. Hopefully they will be addressed soon. Please make sure there is a bug filed for it so we have something to trake.
Hi,
I have developed a sample PhotoViewer quite similar to the one shown in the sample. When I load 12 images (Total 15 MB) from my local system the Total Browser memory reaches to 300MB. I ran the Profiler and it shows that for each image one BitmapData instance is created. These BitmapData instances takes up almost 99% of the total 300 MB Memory. I don't know when and who creates these instances. Is there any way to get rid of this ?
-------------------
Alex responds:
The player creates BitmapData to hold the bitmaps of the 12 images. If your image are highly compressed they could expand significantly. In general, you don't want to load photos of higher resolution than the screen can support. Adobe's Scene7 service is designed to help manage images on the server-side.
I have tried to reduce my huge flash app's memory. At last, it didn't throw exeption in IE. But we can feel the app run more smoothly in Flash Plugin based Browser than ActiveX based Browser.
I optimize my flash app greatly. We found that, we can do same thing with fl.xxx and mx.xxx, mx.xxx usually cost more memory, adn even memory leak. But the fl.xxx counterpart with less memory and no memory leak. So I tried to use Flash more than Flex.
I'm testing Flex 3.0 Charts and seeing horrendous mem leaks for realtime refreshes. Was finally able to tame it a bit by following advice given in SDK-15710 in jirra and doing a window.location.reload() in IE periodically. I was really surpised at the level of mem leaks in flex charts. I thought it had a good penetration on industry given the google /yahoo flash charts but maybe not. Does anyone you know of any high visibility site that used flex charts to display real-time data?
It seems that some(I guess many) memory leaks are due to unoptimized closures.
private function makeA(n:uint):Array {
var a:Array = new Array(n);
for (var i:uint; i a[i] = i;
}
return a;
}
private function doOnce
(ms:uint, f:Function, ...args):void
{
function handler(_:*):void {
myTimer.removeEventListener
(TimerEvent.TIMER, handler);
f.apply(null, args);
}
var myTimer:Timer = new Timer(ms, 1);
myTimer.addEventListener(TimerEvent.TIMER,
handler);
myTimer.start();
}
}
}
can also find the code here:
http://progmeta.googlecode.com/files/ClosureDemo.as
it is clear that loop doesn't close over 'a', yet the memory of 'a' will never be claimed! (from what i checked) if we won't set a = null somehow - exiting the loop will also work; GC will claim the closure, and also its environment
If we explicitly set every unclosed over variable to null then all is well, but i don't wanna do that - when creating a closure the compiler need to keep the captured part of the environment only!
I can only guess that this is the cause of many memory leaks.
This is a major setback for a dataflow infrastructure I'm working on - which is heavily based on closures. :-(
---------------------
Alex responds:
Anonymous functions keep references to the call stack since the call stack's environment is in scope. Once you exit checkMem(), a should go away. If it doesn't, file a bug
Hi Alex,
I'm running a Timer on an interval of 1 second, calling this method when the TimerEvent.TIMER fires.
private function timerHandler( event:TimerEvent ):void
{
if( !_dict ) _dict = new Dictionary( true );
_dict[ "cn: " + _timer.currentCount ] = new Object();
trace( "=============================" );
var prop : Object;
for( prop in _dict )
{
trace( prop + ":\t" + _dict[ prop ] );
}
if( ( _timer.currentCount % 10 ) == 0 )
{
trace( "System.totalMemory: " + System.totalMemory );
//System.gc();
try
{
new LocalConnection( ).connect('foo');
new LocalConnection().connect('foo');
} catch ( e : Error ) {
trace( "GC FIRED" );
trace( System.totalMemory );
}
}
}
The dictionary is weak reference and all the Objects that are created only exist within the scope of the method, but they never seem to be removed from the dictionary? I've tried using grant skinners method and System.gc() to force garbage collection but nothing happens? Am i doing something wrong?
cheers,
James
---------------------
Alex responds:
Yes, you're making a common mistake about Dictionaries. DIctionary keys are weak referenced but the values are not. Also note that String keys are not weak-referenced by Dictionaries.
Hi Alex, Thanks for sharing such a brilliant presentation. I have a question here.
Initially the total memory allocated be 10000 bytes
var a:Object = {foo:"bar"};
//Now some memory will be allocated for the object a
Memory allocated increases to 10000 + 512 = 10512 bytes
delete(a);
Now will the memory allocated decrease to 10000?
Why did this doubt came for me is because you told that garbage collector is triggered by allocation and not deletion.
Please correct me if I am wrong somewhere.
Thanks,
Shameer
-----------------------
Alex responds:
There is no guarantee that memory will shrink after the delete. Some objects in actionscript may be reference counted or the deletion code might allocate something else and accidentally trigger a collection. Or the player will run some code and trigger an allocation and collection. Basically, you should not count on memory shrinking as you delete objects.
When I run my flex application in Firefox, I notice the used memory by firefox keep increasing, but I don't see the regarding memory change used by SWF file? What caused the firefox memory change if it is not caused by swf file?
Where should I find the issue?
I try to run some methode many times to increase used memory, the application crashed finally.
-----------------------
Alex responds:
Use the profiler to make sure actionscript memory is not increasing, and also monitor System.totalMemory. If you constantly create and destroy large (1K or greater) objects, the memory manager may allocate more poorly utilized blocks.
Alex,
Since this post was from March 2007 and the "next release" will have the memory tools, does this imply that Flex3 has these tools?
-------------------
Alex responds:
Yes. FlexBuilder has a profiler that will help you find your memory leaks. I recently posted an article on how to use it.
we have some datagrids contains many records, the memory will increase 7MB if I clear datagrid and refill it.
I don't know it is helpful information for your answer..
I have profiled the application, the memory used by SWF file is only about 20MB when I do anything in the application, but the memory used by firefox is keeping increasing, if I use group function in Datagrid, increase quicker.
I just doubt flex holds the memory from firefox memory every time and never release, but I don't know how it can happen, since swf file itself does not use too much memory.
--------------------------
Alex responds:
It is possible that you are allocating lots of large (> 1K) objects and the memory allocator is creating lots of sparsely used blocks. Try re-using objects instead of creating and destroying
Puh, I m searching now for decades for concret
code snipps/ examples to resolve the memory problems ;-). I learned a lot about defining, removing eventlisteners, weakly referencing etc.
BUT:
Please can someone give a code snipp
how to defenetly remove objects from memory?
And can someone please translate/illustrate this statement with an example:
Make sure you clean up Asynchronous objects directly, nulling these
objects doesn’t unhook them from the Flash player.
- Timer
- Loader
- URLLoader
- File/SQLite
What means “clean up Asynchronous objects directly”???
Should we write something like this:
closing=”cleanMem()”
private function cleanMem():void{
…[WHAT NOW ???]…
}
Should we use deleting properties to remove an object from memory? I am very confused and disapointed about this issues.
-------------------------
Alex responds:
Actionscript uses a garbage-collection memory manager. There is no way to delete something like you can do in C with malloc/free. You have to remove every reference to things and chasing references is hard, but the profiler will help you.
Timer needs to be dereferenced by stopping the Timer, otherwise it continues to be referenced by the player. Things loaded by Loader need to be unloaded and bitmaps should be nulled (See SWFLoader.as).
thx for the quick response Alex.
from your point of view
would this reflect the theories of cleaning up?
I have an instance of a The memory is freeing but it still lacks on some mbs.
Generally is it possible to stop any increasment of memory usage while using an air application?
code-sample:
closing="cleanUp()"
public function cleanUp():void {
trace('............cleanUp..............');
myVideo.ncMgr.videoPlayer.close();//cuts net connecton, triggers no event meanwhile
remAllListeners();//remove all listeners
this.removeAllChildren();//remove all components from displayList
myVideo = null;//set global object to null
ui = null;//set global object to null
cm = null;//set global object to null
dispatchEvent(new Event(Event.CLOSE, true));//bubbles to parent remove me from memory
return;
//todo
//Application.application.register.saveNotePosition(this.nativeWindow.x,this.nativeWindow.y);
}//function
---------
Akex responds:
Use the profiler to help you find leaks. There are some other things you may have to do like cleaning up arrays and dictionaries and stopping timers.
Hey Alex,
I dont use the profiler at the moment because of its complexity- and I m not using the flex builder. Only the sdk and a memory monitor...
Does your comment mean, if I have to clean up arrays, that I have to dereference every variable in a child flex/AIR component/class???
This would be horrible...
Is there any clear and detailed description/list except the g. skinner articles, which elemets have to be cleared/derefenced to completely remove a class object from memory of a flex/air application? It would be so helpfull to get this things all together well organzied in one list or table view with a small code snipp example for any element.
c u st.
---------------------
Alex responds:
All references to an object must be cleaned up (you don't have to worry about cycles (parent -> child & child -
If you null an Array or set its length to 0 (or otherwise remove all elements, you don't have to walk the array to clean its items. My point about Arrays is folks tend to push things in there and build up references over time. Before we had a profiler, I would scan source for addEventListener and make sure removeEventListener was needed and called, check Array, Dictionary and Object variables to see if they are being cleaned up, check Timer and setInterval and setTimeout calls to be sure they are being stopped and cleared.
Why is popups not recommended for flex apps. I noticed that when a popup is removed the memory is almost released instantly
-----------------------
Alex responds:
I don't think anyone said not to use Popups. But they may not be released instantly on removal, so don't count on it.
OK, I ported my flex/air- sdk project to flex builder to be able to use the profiler.
Unfortunately this is not possible without some anoying error triggers while running, which are NOT present if I compile and adl the same things from the shell with the same flex sdk and air sdk flex builder currently uses. Very weird ;-). I m to 99% sure that I configured the project and flex builder right (additional compiler arguments etc.).
Some of the errors are:
VerifyError: Error #1053: Illegal override of play2 in fl.video.DynamicStream.
ReferenceError: Error #1065: Variable WindowMinimizeButtonSkin_macMinDownSkin is not defined.
ReferenceError: Error #1065: Variable _macCloseButtonStyle__embed_css_mac_close_up_png_1447874772 is not defined.
ReferenceError: Error #1065: Variable _VDividedBoxStyle__embed_css_Assets_swf_mx_skins_cursor_VBoxDivider_1501504583 is not defined.
ReferenceError: Error #1065: Variable _macCloseButtonStyle__embed_css_mac_close_over_png_998131734 is not defined.
ReferenceError: Error #1065: Variable _winMinButtonStyle__embed_css_win_min_up_png_632880618 is not defined.
ReferenceError: Error #1065: Variable _winMaxButtonStyle__embed_css_win_max_over_png_706412308 is not defined.
ReferenceError: Error #1065: Variable _MenuStyle__embed_css_Assets_swf_MenuCheckEnabled_126362086 is not defined.
ReferenceError: Error #1065: Variable _winRestoreButtonStyle__embed_css_win_restore_over_png_233844520 is not defined.
In this project I use the new FLPlayer-Lib 2.5.X for Flex from Adobe Labs.
I could imagine that all these errors are depending on conflicts with the default build path librarys of Flex Builder. But this stuff is very hard to recover. Can you follow? Do you have any suggestions to solve
this problems. Would make me happy to get this things working :-).
[Flex 3.3.0, AIR 1.5]
---------------------
Alex responds:
If you use your working project (and add -debug to MXMLC options), you should be able to use FlexBUilder's Profile External Application capability to debug the AIR app.
Hi Alex,
Our application runs at around 25mb, as shown by both System.totalMemory and the profiler. This value is very stable, and no matter how long we run it, it always GCs back down to this.
However, when running in IE or Firefox, the memory shown by the task manager as being assigned to them starts off at ~190mb and goes up to 350+mb after only a few minutes. The Flash player still reports the same 25mb we expect. What could be causing this?
------------------
Alex responds:
System.totalMemory and the profiler do not show memory used by the operating system and browser to do its work, nor does it show memory used by the JIT or the Flash rendering system. We've recently seen that cacheAsBitmap and scrollRects can cause the rendering system to create large buffers. Also, there are known issues with the browsers use of memory when buffering files/streams for Flash. Flash things it has released the buffer, but the browser holds onto it "forever" (often it will release it when you minimize and restore the browser window). That remains an open investigation.
Guys
I am running in to a major memory leak issue and would appreciate it if someone can help -
I use a data grid and set the data provider to an arraycollection. Now i update the arraycollection (several (like 20 - 50) times per second) and saw that this would refresh the whole data grid and spike up the CPU. So I decided to separate the data source update from the data grid update (UI update) and to suppress the datasource automatically updating the data grid, i decided to set disableautoupdate but to my dismay this has create a memory leak situation as apparently Adobe doesn’t disable it but rather queues the change events …
so to solve i embarked on a series of solutions which all doesn’t solve it or creates its own issues -
1. Create a new class extending datagrid and overwrote the
override public function set dataProvider(value:Object):void
{
super.dataProvider = value;
//super.removeEventListener(CollectionEvent.COLLECTION_CHANGE, collectionChangeHandler);
collection.removeEventListener(CollectionEvent.COLLECTION_CHANGE, collectionChangeHandler);
}
2. i set disableautopupdate and set up a timer to do enableautoupdate() and disableautoupdate()
- this works but everytime the timer kicks in, i can see the CPU spike
3. Overwrote
override protected function collectionChangeHandler(event:Event):void{
return;
}
this works for the most part but on load it doesn’t display data till i resize the panel …
Now, let’s not focus on why i need to update 20 - 50 times a second, it’s a trading application and quotes stream in that fast. Let’s assume that’s the right problem to solve …
Any help anyone can provide is extremely appreciated … i am posting here since it seems like you guys are interested in memory leaks …
-------------------
Alex responds:
For high update rates, I recommend making the data objects not-bindable so they don't dispatch change events and cause collection events. Then have the data objects dispatch an custom event when updated and have the renderers listen directly for changes to the item they are rendering. Don't replace items, just update their prices, etc.
Hi Alex,
I am working on a large project in which one of the module is opening on a popup. This module contains slider component to adjust graph values. For the very first time slider thumb dragging performs very smooth and works well. But if I opens the same module for multiple times, the slider dragging performance decreases gradually. Some point of time it stops working. Sometimes systems hangs and browser needs to be closed. I have checked with task manager each time memory usages increases. I am using PopUpManager.createPopUp for opening the module. Please suggest me how to rectify this error.
Regards,
Susant
------------------
Alex responds:
Use the profiler to see if memory is leaking. There's a separate post on my blog about how to use the profiler
Hi Alex!
I've read lots about Flex, started to use it like two months ago.
Converted a very large TCP client/server (C++) Flash project into Flex, and I can say that I'm definitely glad that I did so!
Now, I've mentioned the server's programming because I want to mention that even though there are HUGE advantages using Flex over Flash, Flex has a lot in order to become as handy as C++, and we know what success is C++.
First and most importantly - where are class destructors?
Secondly, the whole attitude that the Flex designer seem to had is not complete;
Much of the stuff that I'd like to handle by myself seem to be "taken cared of" by the Flex framework - that's bad.
For example, this whole memory leaking issues.
I'm a programmer - I know what's good for me - let me deallocate my own stuff. Why FORCE me use some GC? Because it's a nice sounding feature?
See my point?
On a final note I just want to say as a "Flash to Flex migrator" that Flex gone a good way yet has some issues, as described above.
Thank you.
---------------------
Alex responds:
GC is the current popular memory management scheme. Java uses it and we expect more folks coming to AS from Java than C++
Hi alex,
I went through the process of detecting create/destroy memory leaks according to your presentation, but I fail to understand how you identify circular references in the "object references" window.
If I understand correctly, according to the presentation, when you expand an object referencing LeakyDialog and find LeakyDialog's id as a reference to this object, it is considered a circular reference .
However, in the classic memory leak of systemManager.addEventListener(MouseEvent.MOUSE_DOWN, mouseDownHandler); Leakydialog holds a reference to the systemManager through it's systemManager property, but it's not considered as cyclic.
What am I missing here?
Thank you.
------------------------------
Alex responds;
You can have a reference to a parent or grandparent without causing a leak. What matters is whether there is a reference from a "GC Root" like the Stage to an object. LeakyDialog having a reference to the SM and the SM having a reference to LeakyDialog is a cycle, but the path from SM to LeakyDialog is a problem. Other cycles go to children or other subordinate objects from LeakyDIalog and back again.
Hi Alex,
I have a modular application that loads movies into new ApplicationDomains. Many of these movies subsequently load native components. Once that component is placed on the display stack the sub application can never be released from memory. Without the native component, memory is freed as expected when the application is unloaded. I can't figure out what is happening in the native component that prevents it from being freed. Any suggestions?
-----------------------
Alex responds:
Not sure what you mean by "native component". The profiler should be able to help you figure out what is holding a reference to the module.
Hi Alex,
I am working on Flex 4.0 beta version. Do you have any idea that how Flex 4.0 is dealing with the memory leaks which we had in previous versions of Flex.
I am going to design a huge system and have take care of memory very properly.
I have cotagorised few aspects where memory needs to be managed:
· module load and unload
· Manual and automatic garbage collection
· Usage of any API providing info on memory usage
· object hierarchy
of child and parent load and unload.
· Cairngorm application framework
· costlier objects
· strategy
I have already researched alot on these aspects and can easliy see some workarounds by different consultants but have not got any standard way by which we can do the GC.
Can you help me out in giving the right approach for above mentioned things.
Thanks
Indro
I recently came across your blog and have been reading along. I thought I would leave my first comment. I don't know what to say except that I have enjoyed reading. Nice blog. I will keep visiting this blog very often.
Maria
http://memory1gb.com
Alex - I have been trying to determine the cause of a potential leak to no avail and finally I thought I will check with the guru... So here goes..
I have a fairly large flex app (200M resident memory and grows from there) that comes up and after about a few minutes starts to increase its footprint (in steady state) and continues to grow to a point and then stops for a while. I tried to profile the application and the profiler does not show any loitering objects when I take snapshots just after the complete load and when this phenomenon starts (about 1 - 2 min into the app load)(I have also severed all data connections to the app so nothing really should be changing). Then I noticed on the profiler the only thing that changes when this happens is TimerEvent objects get created. The cummulative memory for the object keeps on increasing steadily but the memory column always stays at zero indicating this cannot be the cause of the leak. I also tried to put breakpoints inside all the known timers in my code to see what ticks and I cannot see anything ticking on my end. Now the question is how can I get a stack of who is actually triggering this event and why? I tried to use the sampler API but that for some reason does not seem to work on this specific project probably due to size (as the same code works on smaller prj I have). I also unsuccessfully tried to monkeypatch TimerEvent to set a breakpoint but I guess that does not work as it is native player code(probably)... So basically I am out of ideas at this point and would really appreciate if you could give me some hints on how to track down this potential leak with TimerEvent?
Flex 4 isn't doing much differently from Flex 3. Both SDKs still run on the Flash Player. I recently posted some information on what we know about unloading modules. There is a known hack to try to force garbage collection. But the basic principles are, don't new objects, try to re-use existing ones (unless you have 1000's of objects), use model-view or MVC to get fewer interconnections between pieces so you can remove things, use the profiler to see what the biggest consumers of memory and cpu are.
If you own all the source code, I'd check to see who is creating/attaching timer events, setTimeout and setInterval calls. Maybe someone is adding more and more intervals and timers.
Hi there,
I admit, that I didn't read all of the above posts, but I think my question hasn't been addressed yet: I'm testing some AS-App in the stand-alone flashplayer 10 and it seems it doesn't even clear the memory when I close it (I'm tracing System.totalMemory and every time I start the player the app starts with the amount of memory it had when I last closed the player). Shouldn't flashplayer garbage-collect everything on closing, independent from my code?
regards,
davy
I have run lots of tests and have never seen that, although System.totalMemory can have different starting values. Are your allocations small enough that they'd be within the range of variance in System.totalMemory startup values?
Or is your test saving and loading stuff from sharedObject and actually accumulating data as you go?
If you have a simple test case that shows the problem, file a bug.
Hi Alex,
thanks for the answer. No sharedObject involved in my app. I guess my allocations could be within the range of variance, they just seem to vary only upward. I'll try to construct a simple test case.
Check out this blog for some Flex memory stats
Flex Memory