Categories
Articles

Flex, Flash and Actionscript 3 Memory

I have been in on or called in on Flash and Flex applications that perform slowly.

When there is a back end, I recommend an isolation process to eliminate the move from the equation. This includes all data and dynamically loaded assets and movies.

When the backend is out of the way then the focus is on memory. This requires providing calls to memory information as the application is navigated. I provided basic shell code that works below you can consider for integration into a memory monitoring module for your application.

In designing Flash player movies whether you are using Flex or Flash should always side on caution in creating objects and loading assets. Its garbage collector works when it thinks it is ready. As well you need to care for the removal of event listeners when you remove objects.

The System class contains a property totalMemory. Here is an example so you can learn about it.

MemoryMonitor.as

package {

   import flash.events.TimerEvent;
   import flash.utils.Timer;
   import flash.system.System;

   public class MemoryMonitor
   {
      private var timer1:Timer = new Timer(1000, 0);
      private var timer2:Timer = new Timer(1000, 0);
      private var totalMemory:int;
      private var totalMemory_last:int = 0;

         public function MemoryMonitor():void
   {
         trace("MemoryMonitor()");
         timer1.addEventListener(TimerEvent.TIMER, _displayTotalMemory);
         timer2.addEventListener(TimerEvent.TIMER, _displayTotalMemoryOnChange);
      }

      public function displayTotalMemory():void
      {
         timer1.start();
      }
      public function displayTotalMemoryOnChange():void
      {
         timer2.start();
      }
      private function _displayTotalMemory(event:TimerEvent):void
      {
         trace("MemoryMonitor.displayTotalMemory() - System.totalMemory:\t\t" + totalAsMB(System.totalMemory) );
      }

      private function _displayTotalMemoryOnChange(event:TimerEvent):void
      {
         totalMemory = System.totalMemory;
         if (totalMemory != totalMemory_last)
         {
            trace("MemoryMonitor.displayTotalMemoryOnChange() - totalMemory_last:\t" + totalAsMB(totalMemory_last) );
            trace("MemoryMonitor.displayTotalMemoryOnChange() - System.totalMemory:" + totalAsMB(totalMemory) );
         }
         totalMemory_last = totalMemory;
      }
      private function totalAsMB(totalMemory:int):String
      {
         return (Math.round (((totalMemory / 1024)/1024) * 10)) / 10 + " MB"
      }
   }
}

Flash Movie frame 1 Actionscript

import MemoryMonitor;

var memoryMonitor:MemoryMonitor = new MemoryMonitor();

// Display memory every 1 second
memoryMonitor.displayTotalMemory();
// Display memory every 1 second if it changes
memoryMonitor.displayTotalMemoryOnChange();