Does Your Tween Stop In The Middle?

Branden and I were working in the office today when Branden came over and asked me if I've ever run into the following problem:

You are creating tweens using the Tween class in AS3. These tweens are inside of a method (or a loop). The tweens appear to work fine, except, they stop in the middle without explanation. As it turns out, I had run into this problem before. While working on a previous project, I had a series of tweens moving around a Rectangle object inside a class method. Halfway through the tween, it stopped for no apparent reason. After using everyone's favorite inter-web fast-food chain, Google, I determined that the issue must be due to garbage collection. I typed in "AS3 tween garbage collection", and found that my problem had been solved and discussed by Scott Morgan. Here's his blog post about it.

The solution, as described by Scott is to create class properties for your tweens instead of local variables. As I described this to Branden, he noted a potential problem with this solution. When you use class properties, the Flash player will allocate space for those properties, even when you are not using them. Why is this a problem? Well, imagine you can potentially have hundreds of instances of a class, where each instance contains private properties for 5 tweens. This could significantly hurt the performance of your application since you will have allocated space for all of those tweens, even though the tweens are not running. Needless to say, while this is a good solution, and great in a pinch, ultimately, you will have problems for large numbers of tweens.

So, how do you solve the secondary problem of allocating space for tweens that are not running? Is there a way to use a class property to store the tween (so it is not killed by the garbage collector), without actually allocating space until the tween is needed?

The answer: DICTIONARY!

Instead of creating a property for each tween you use, instead, create a single property of type flash.utils.Dictionary. The Dictionary class allows you to create a set of dynamic properties, without allocating the space for them until the property is actually created. Additionally, you can also use an object reference as a key in a dictionary, which can be a very powerful tool. Once you have your dictionary, inside the method (or loop) that creates the tweens, store the tween object reference as the key in the dictionary. Once your tween is complete, delete the key and your tween will be collected by the garbage collector.

Here's an example:

How to pronounce our name…

Just as a public service message - it's not "auto-mata" - it rhymes with "manamana" as demonstrated by the Muppet Show:

(Thanks to Tom Pizer over at Performtech who dug up the video)