Garbage Collection and Memory Leaks

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.
Download Presentation
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.
Download Sample

77 Responses to Garbage Collection and Memory Leaks

  1. Jake says:

    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.

  2. Adu tt says:

    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.

  3. Eric says:

    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.

  4. Thomas says:

    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.

  5. Thomas says:

    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.

  6. Joey says:

    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:
    ———
    I’ll try to find time to look into it. But please file a bug if you haven’t.

  7. Ian Davies says:

    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

  8. 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.

  9. Rob McKeown says:

    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.

  10. Li says:

    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.

  11. 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

  12. Van de Velde Olivier says:

    Hi, searching for memory leaks with Flex Builder 3, Beta 2, in a strongly module based application, I found the following:

    usage of instance members instead of static members can easily be detected with the profiler (replace by static members where possible)
    usage of weak references and / or removal of eventListeners after consumption of the event (if posible) helps reducing the memory usage
    moduleLoader.unloadModule leaks memory, use moduleLoader.url=null instead
    module memory is freed at arbitrary times (not at unload)
    runnning debug version of modules leaks huge amounts of memory no matter which container is used
    declaring modules as modules in the configuration of a flex builder 3 project (and not as applications like in FlexBuilder 2) and optimizing for a specific application reduces module size drastically
    forcing garbageCollection (double LocalConnection.connect hack) is necessary in order to measure leaks and to keep memory under control

    —————-
    thanks

  13. Jackflit says:

    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.

  14. Kev says:

    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

  15. Van de Velde Olivier says:

    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 :

    use the release version of the module swf
    uninstall the debug flash player (“uninstall_flash_player.exe”)
    install the release version of the flash player (“install_flash_player_active_x.msi”)

    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.

  16. Tom says:

    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.

  17. Jylaxx says:

    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.

  18. Pedro says:

    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>
    ;
    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.

  19. Sam says:

    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.

  20. Cliff says:

    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.

  21. Manan says:

    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.

  22. jackflit says:

    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.

  23. Kumar Pandey says:

    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?

  24. Fractal says:

    It seems that some(I guess many) memory leaks are due to unoptimized closures.

    package {
    import flash.net.LocalConnection;
    import flash.utils.Timer;
    import flash.events.TimerEvent;
    public class ClosureDemo {
    public function checkMem():void{
    var a:Array = makeA(1024 * 2000);
    function loop(x:uint):void {
    if(x%1000 == 0) { trace(x) }
    doOnce(1000, loop, x+1)
    }
    loop(0);
    // this function and its environment
    // should be marked & sweeped by the GC.
    // so referencing a should not pose a problem
    // in any case.
    function clearA():void {
    a = null;
    doOnce(1000, triggerGC);
    }
    // if we remove this line a will never(as far as i can tell)
    // be claimed by GC.
    doOnce(3000, clearA);
    }
    private function triggerGC():void {
    trace(“triggerGC”);
    try
    {
    var lc1:LocalConnection = new LocalConnection();
    var lc2:LocalConnection = new LocalConnection();
    lc1.connect( “gcConnection” );
    lc2.connect( “gcConnection” );
    }
    catch (e:Error) {}
    }
    private function makeA(n:uint):Array {
    var a:Array = new Array(n);
    for (var i:uint; i
    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

  25. james says:

    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.

  26. Shameer Salim says:

    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.

  27. Feng says:

    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.

  28. Matt says:

    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.

  29. Feng says:

    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

  30. stevie says:

    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).

  31. stevie says:

    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

  32. stevie says:

    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 –

  33. Mayank Vora says:

    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.

  34. stevie says:

    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.

  35. Thomas Vian says:

    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.

  36. sai says:

    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.

  37. Susant says:

    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

  38. Eli says:

    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++

  39. Ilan says:

    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.

  40. Jonathan says:

    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.

  41. Indro says:

    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

  42. Maria says:

    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

  43. Vivek says:

    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?

  44. Alex Harui says:

    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.

  45. Alex Harui says:

    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.

  46. davy says:

    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

  47. Alex Harui says:

    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.

  48. davy says:

    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.

  49. II says:

    Check out this blog for some Flex memory stats
    Flex Memory

  50. Jordan W says:

    I’ve had the same problem as Davy before, and ended up just having to close the Flash IDE and reopen it (System.totalMemory when called in a “test movie” from the Flash IDE shows the memory of the movie plus (some?) memory of the IDE, so totalMemory getting larger is the Flash IDE getting larger). I admit that this is terribly inconvenient, but I found no way to stop the “accumulation”, which would grow until it would cause OS out of memory errors. What would cause the IDE to hold on to memory from a “test movie”? I can’t say, but it makes sense as the test movie is run as a subprocess of the IDE.
    The application that was causing this was an image editor. When using a ShaderFilter, when you set the shader, it doesn’t actually use the shader you give it, but a copy instead. What was happening is that Flash was refusing to gc the (copied) Shader, even when I got rid of all references to it’s ShaderFilter. This was for some reason creating Mb’s and Mb’s of memory usage every time I ran any filter. Setting the shaderFilter.shader to a new (blank) Shader solved the problem. But the real issue, internal copies of “our” objects, might be an underlying problem for Davy’s issue as well.

  51. Jian says:

    Hi, Alex
    I am developing an application using Flex Tree component.
    I found there may be a memory leaks issue when I update data provider of the tree. I use profiler to take snapshots of memory. The number of instances are not increasing but the memory is increasing without reaching an actual peak.
    Then I analyzed my code, I think one possible reason for the memory leaks is the expand items of the tree. Then to rule out the issue introduced by me, because I am customizing the Tree component a little bit, I create a simple test case, which is published at http://sites.google.com/site/jianspublic/home/flex-tree-component-memory-leaks-issue
    In the test case, I have two buttons, one is “Change Data Also Expand” to update the data provider with 1000 nodes and expand the root node, the other one is “Change Data Without Expand” to update the data provider but not to expand. So the only difference between these two cases is whether expand the root node.
    Via the memory monitor, you can see if you click “Change Data Also Expand” button, say 10 times, the memory will increase by almost 1MB for each time and will never reach a peak; while you relaunch the flash by refreshing the page and when you click “Change Data Without Expand” button, the memory will kind of fluctuate around a number. So I guess the openItems property of the Tree component has memory leaks issue.
    Would you please verify this issue for me? This issue is important to me because my application requires to open the Tree for the user each time and I can see the memory of the application keeps increasing.
    Thanks in advance.

  52. Gawie Kellerman says:

    Firstly, this is quite an old thread – so chances are nobody will read/comment on my findings.
    Basically, I also noticed the various memory leaks (especially and most importantly to me – with SWF loader). So, without trying to spend countless hours I did the simplest thing imaginable (with the WORST results imaginable) and have to get to a conclusion that Flash just is useful for flash-per-page or brochureware and NOT for real big intranet sites (which is supposedly one of its main selling points).
    WHAT YOU DO:
    Compile the Explorer application in the samples directory.
    Run this in any browser and go down and up through the list (which loads and reloads the various control demos)
    You will find that the memory, even though it sometimes goes down, continuesly grows until the browser crashes.
    I have done this with every SDK from 3 to 3.5
    I have done this with Flash 9 and 10 (latest), both debug and non-debug.
    I have done this with leading browsers, Firefox (various) and IE 6,7 AND 8!
    And just to top it off… If I press the button too quickly; then an application error pops up (one of those ActiveX crashes thingies which I am not even going to try to represent here).
    Seriously Adobe – WHAT ARE YOU DOING?? IS THIS ISSUE SO BIG AT THE CORE THAT THERE IS NO RESOLVE – OR ARE WE TRYING TO USE THE PRODUCT IN AN UNINTENDED WAY?

  53. Gawie Kellerman says:

    PS: Doing a non-debug compile does nothing to its leak and die fate 🙁

  54. Alex Harui says:

    I don’t have time to look at your test case, but openItems will definitely keep objects in memory. In theory, once you close nodes, they should get removed from openItems. If for some reason you don’t close nodes, you should find a way to clean up references in openItems.

  55. Alex Harui says:

    The Explorer app may never have been checked for memory leaks and could have bugs. Many companies have used the profiler and been successful in deploying Flex apps that don’t have leaks. If your app is having problems, use the profiler to see what is going on, see the other posts on my blog on this topic, and ask for help from support or on the forums.

  56. erik h says:

    heya Alex.
    on the topic of some browsers (IE) keeping rendering data in its own buffer and hence holding onto memory even though Flash has supposedly gotten rid of it.. What’s the deal there. I understand that it’s not technically a problem on Adobe’s end but.. it’s pretty nasty. Any application that relies on loading a large amount of data from time to time and hence relying on the memory being deallocated at some point will have some serious problems.
    Any workaround at all? Especially related to the cacheAsBitmap render buffer memory bug in IE and some other browsers.

  57. Alex Harui says:

    Lots of folks are successfully handling lots of data so I don’t think we’re seeing this very often if at all anymore. Make sure your app is not leaking in some other way.

  58. nice post , thank you for your efforts.

  59. moncler says:

    Good to know this information.It’s useful to me. Thank you for sharing with us.

  60. Ben Humphrey says:

    Alex, thanks for helping everyone out with your posts. I am using Flex4 and are are getting the same thing for our large application that goes from 40M to 326MB over time, and just sitting there too with no user interaction. I did a profiler session and noticed that XML had one of the largest leaks. We are sending and receiving big chunks of XML to our .Net backend, and was wondering, what are some suggestions to clean up XML other than just setting things to null? Any tricks?

    Also, we have a bunch of different screens, and am using the Pure MVC model, and it seems like if we go to the home screen, then our admin screen, then the home screen, and back again to the admin screen, the admin screen is still alive and back to the same state as it was. Each screen is registered as a [SkinPart] to the main application. How would i completely refresh that skin part and/or mediator each time I change states and switch screens? Otherwise every screen we go to just keeps being saved in the background and making a huge amount of memory. Thanks!

    • Alex Harui says:

      I believe there is a dispose() method in the latest players that will force some cleanup of XML overhead

  61. mini netbook says:

    Yeahh Your artical was great..

  62. ecar26 says:

    I have a view which contains a datagrid with a item renderer, the dataprovider is a list that i populated from a java back end.
    If I changed the view I clean the list but when i go back to the view with the datagrid it shows a new list but in memory (using the profiler) i see that the old objects remains there and make the application to increase its memory easily.

    Any ideas o how to resolve this issue?

  63. Trying to figure memory leak issues out is driving me insane. I saw a link on stack overflow for a memory monitoring component, but its pointing to the right place anymore. Whats a good way to find memory leaks in super complex apps, like games, using Flash only?

    • Alex Harui says:

      I would hope even a “super complex” app is modular so that subsystem can be isolated and individually tested for everything, including leaks. Then you should be able to hook up the Flash Builder Profiler and find out what is going on.

  64. Vivek says:

    We have developed very big web application in Flex 3.0 using Cairngorm framework.
    It is very nice to get good response from user.

    Please have a look try using user : administrator@diaspark.com pwd: jewel
    When I open any transaction page & close & re open again n again, I found that memory never released.

    Browser memory usage continously increasing. Please suggest what to do.

    Vivek

    • Alex Harui says:

      Maybe the profiler post on my blog will help you understand how to use the profiler to diagnose the problem.

  65. Ravindra says:

    Hey Alex, I am working on a large flex application. Facing many memory leak problems with it. I tried profiler, but i couldn’t analyse the result of the profiler. Where do i get some detailed documentation on how to analyse the result of Profiler and fixing the memory leak ? Or if you have some documentation with you please share it. Thanks in advance.

  66. Johan says:

    Alex, thanks for helping us out on gc. At the moment we are evaluating to use flex in a large application (we are thinking of using the gantt chart from ilog elixir).

    Garbage collection and memory management is one of the concerns I have but the explanations I found here an elsewhere lead me to the conclusion that it will be manageable provided we build in a lot of discipline and combine it with the profiler when things get leaky. There remains however one issue that could be a sticking point.

    It is mentioned in

    http://tomgabob.blogspot.com/2009/11/as3-memory-management.html

    that groups of objects that should be gc-ed are not because the group is too big:

    “In practice (maybe this is in the spec, I don’t know, but I missed it if it was), there seems to be a limit on just how big an orphaned group of objects can be before the GC just gives up and assumes the whole group is still being used.”

    Is this true and if so what is the reason for this? If so, what kind of magnitude does such a group have to have in order to prevent it from being gc-ed?

    regards

    • Johan says:

      The issue mentioned in the other post seems to be related to item 8 in the following post

      http://www.iampj.com/

      “Remember, Flash GC is not forward progressing and incremental. If a large object graph cannot be analyzed in the limited time the GC gets, all objects in the object graph will start leaking.”

      Is there technical documentation where this kind of information is explained?

      • Alex Harui says:

        I don’t think there is Adobe documentation for how gc() works. You can see the code in the Tamarin project source code. The garbage collection implementation could be modified or overhauled in the future. In my experience if you are “outrunning” gc, you might want to look into recycling of objects and other optimizations to free up time for gc to run. If you have such a huge object graph that gc can never finish, you’re probably experiencing other issues as well and simplifying the object graph might have other benefits

    • Alex Harui says:

      The primary goal of the gc implementation was to try to avoid hiccups in animations. I don’t know the details of the implementation to that degree, but there is a chance that it simply can’t get it done in the time it has to do it, and also a chance that data values in an object can alias as object references. I’ve only seen gc fall behind when creating tons of objects and often there is an alternative approach that will not only solve the gc() issue but improve performance as well.

      I’ve never seen the aliasing problem, but it is theoretically possible.

      • Johan says:

        Alex,

        Thanks. We are going through a checklist of potential pitfalls for using Flex on our next project , one of which were the unknowns about garbage collection. But after my research and initial tests I am reassured this can be controlled in our scenario and should not be a showstopper for starting a larger proof of concept.

        regards
        Johan

  67. Tahir Alvi says:

    hi,

    How remove garbage from Flash builder automatically or set the timer for that event?

    • Alex Harui says:

      I suppose you could use the LocalConnection hack on enterFrame or a timer. You might be better off implementing recycling of objects if you are creating a lot of objects.