The last few months I have been busy integrating Flash swf files into bigger (mostly Flex) projects. Because Flex websites might hog the memory due to large amounts of graphical elements and sometimes enormous huge amount of dynamic content, I had to keep an eye out for performance drops.
There have been a lot of optimization tricks for ActionScript 3, mine listed here will probably already be somewhere on one or another guru’s blog. But I’d like to list them again because I think there is a need to educate beginning (and sometimes advanced) ActionScript developers about the different performance capabilities. Please mind that this is NOT a complete list in any way. These optimizations are the ones I had to use the most lately.
Trick 1:
Always create a destroy() function on your sprites/movieclips/shapes when they have a custom class applied to them or when they are just standalone custom classes.
The destroy function should be responsible to do the following:
- clear ANY listener that was used in the custom class, use hasEventListener() to check if there is a listener added in the first place!
- remove the children of the custom class
- set the removed child to null to clear the reference: myChild = null;
Example:
/** * Clean up the current circle image the gain back performance. */ private function cleanUpCurrentCircleImage(event:Event):void { currentCircleImage.destroy(); if(currentCircleImage.hasEventListener(CircleImage.ANIMATED_OUT)) currentCircleImage.removeEventListener(CircleImage.ANIMATED_OUT, cleanUpCurrentCircleImage); if(currentCircleImage.hasEventListener(CircleImage.ANIMATED_IN)) currentCircleImage.removeEventListener(CircleImage.ANIMATED_IN, timeOutTillNextImage); removeChild(currentCircleImage); currentCircleImage = null; showImage(); }
Trick 2:
A useful trick when you have a lot of BitmapData. You have to know that a lot of BitmapData just keeps sitting in the memory although you removed the container Bitmap. Don’t ask me why the Flash Player does this but is very annoying as my colleagues at BoulevArt noticed while adding an image of 10 000 by 3000 pixels to the stage. They sliced up the image in different images and loaded the images that were needed at runtime. But they also had to delete the images again when they were not necessary anymore.
Solution: the BitmapData class has a very usefull dispose() function you can use to get rid of the real pixel data.
var myBitmap:Bitmap = new Bitmap(); myBitmap.bitmapData.dispose();
Trick 3:
Use a memory monitoring class so that you can keep an eye out on the -real- memory usage of your Flash. A good, but hard to find class is: ActiveGraph created by rezmason.
I added the class here to make it easy for you. Don’t forget to thank rezmason for the great class :p.
That’s it for now. Not that much hu? Well, this is certainly not the end, keep an eye out on my blog because I feel we have to do a lot more performance tweaking :p
