Flash AS3: Garbage collection and the importance of recycling

Posted on February 21, 2009


Today I am optimizing my portfolio site. It combines both dynamically generated- and static items. Now the static items pose no problem. The dynamically generated do.

Garbage collection

First of all: the garbage collector of Flash 9 sucks. Objects/movieclips with either/ or

  1. Events
  2. External references to-

Will sustain in memory. Apparently the next release of Flash will deal with this issue with some kind of “Kill” or “Die” or “Dispose” function. For now, we have to be creative.

The problem of Flash’s lazy/sloppy garbage collection is not the only thing that bugged me.

“Memory leaks”

In my portfolio site I create tiles with an image inside the tile. The tile itself is a button. Each time I switched to another Panel to present other data, the memory use of that Flash movie increased with 20MB to 24MB. First I blamed the images I loaded inside the MovieClips. But when I did NOT load the images into the movieclips, the increase/leakage stayed the same.

The culprits: 4 tiny tiles x 5MB each
4 tiles = 20MB memory leak

The tiles are the only variable element in the site. As 4 new tiles are created with every new page loaded and are hard to dispose of, the increase in memory use will be at least 20MB with each new page view, since old pages are not stored but (should be) disposed of. Since the garbage collection of Flash is crap anyway I decided to drop Plan A (write a garbage cleaner) and go for plan B.

Plan B: The short term solution for Memory Leaks: Recycling

When the garbage truck does not come along and rubbish piles up around your house what can you do? Recycling the old crap to avoid more rubbish to come into your house is one of the easiest ways.

Once I create my objects on stage, I keep tabs on them via an Array. When I “destroy” them, I simply remove them from stage and make them available for re-use. Instead of creating new instances of my interactive objects I run through the array with already created ones, clear their settings and call them back on stage. Only when more movieclips are required I create them.

My current solution is rather straight forward since the array is per  Content Pane (3 in total) and there is only one stip of tiles.

The memory leakage is now “only” 1 MB per new view.

Next step

The next step to take is to create a solid pattern for recycling assets (including images and SWFs). When time allows I will improve my current solution and release it as open source.

Posted in: ActionScript