A performance issue that most Flash Developers encounter at some point in time, in most cases can be caused by a memory leak. Objects pile up on top of each other, Flash’s garbage collector notices that some of them still has a reference somewhere in the application, and sometimes it may even give up marking the objects during a memory sweep because the “Object-References Islands” are too big to process the whole way through in one cycle.

Obviously, there’s no better way to eliminate this problem by ensuring that you break all the necessary references of your objects, and their member variables as well.

Think of it like a gold rocker cradle [see illustration below] which was used as an old manual filtering process to collect gold.
The smaller the size of the dirt (the object islands)… the easier it is for it to pass through (get garbage collected) to leave the gold (the necessary objects) by itself.

A gold filtering process tool

A gold filtering process tool

Here’s an example of a class that makes use of a “destroy()” method to make sure it discards all references that its properties were holding on to.

package {
	import flash.display.Sprite;
	import flash.events.Event;
	
	class Bomb extends Sprite {
		private var _countdown:int =	-1;
		private var _location:Point =	null;
		private var _target:Sprite =	null;
		
		public function Bomb() {
			_location =	new Point();
		}
		
		public function destroy():void {
			//Remove event listener if it's still running:
			if(hasEventListener( Event.ENTER_FRAME )) {
				removeEventListener( Event.ENTER_FRAME, onBomb_EnterFrame );
			}
			
			_countdown = -1;
			
			_location = null;
			_target =	null;
		}
		
		public function mountOn( pTarget:Sprite ):void {
			_target =	pTarget;
			
			_countdown = 50;
			
			addEventListener( Event.ENTER_FRAME, onBomb_EnterFrame );
		}
		
		private function onBomb_EnterFrame(e:Event=null):void {
			if((--_countdown)<=0) {
				explode();
			}
		}
		
		public function explode():void {
			//Remove event listener if it's still running:
			if(hasEventListener( Event.ENTER_FRAME )) {
				removeEventListener( Event.ENTER_FRAME, onBomb_EnterFrame );
			}
			
			//Put some damage on the target...
			//Example:
			_target.alpha -= 0.1;
			
			//Finally, get rid of this object
			destroy();
		}
	}
}

Note how the handling of event listeners here is attempted to be removed in two areas. The reason being – in this scenario, if the bomb is “destroyed” prematurely to the explode method, then it will make sure it stops the ENTER_FRAME listener.

Of course, be aware that this is only one of the many steps to improve your Flash application’s performance!

Follow the link below to continue your journey:
#INSERT NEXT TIP LINK HERE#