Best Practices when Listening

* Try to always use a weak listener, even though it's extra typing. The classes of bugs you are exposed to with strong listeners are mostly running out of memory, taxing the garbage collector, and killing performance as you take memory off the heap -- they creep up and are hard to detect. The classes of bugs with weak listeners are functionally worse -- but easy to detect -- stuff just doesn't work because the listeners got GCed (they are a little less performant too, due to tracking their weak-ness).

* When writing weak listeners: Make sure that objects you are listening on will not get prematurely garbage collected and are attached to something -- either the class, or some static Singleton.

* Make sure the object will get garbage collected eventually and write a comment about it.

* Assume that all weak listeners and objects will never get GC'd and will keep listening forever -- code for this. In other words, explicitly remove listeners when it is IMPERATIVE that you do not receive any more messages, do not rely on setting a parent to null to break the cycle.

* You DO NOT have to remove weak listeners if it doesn't matter if they continue to receive events until they GC -- e.g. a mouse move handler -- once you've removed the object from the display list, it doesn't matter that this handler MIGHT run. If you code your handlers to guard against runtime errors, then you never have to remove weak listeners. And if the listeners are still receiving after a long while... then you have a memory leak and the object you are listening on is not getting GC'd (see this post).

* If you are going to skip removing a listener, DOCUMENT IT at the line where you add the listener. If you won't document it, then don't do it.

* This is tricky stuff, so treat listeners with respect like you would NEW and DELETE in C++. Work them out in your head -- document the hell out of them. They are expensive and cause almost all memory and (many) performance leaks.

Random() Performance Tips

* Perceived performance is more important than actual performance, and is cheaper to implement. Learn about how to fake speed in progress bars, and never, ever, ever, ever let Flash lock up while doing processing -- break work across frames and do it asynchronously -- keep the UI responsive even if it's modally locked.

* Initializing variables to null is unnecessary, costly, and distracting (when you're trying to read code -- null or zero unless otherwise specified).

* Eliminate "this." wherever possible -- this may be outdated, but in the past it produced better bytecode.

* Don't use coding conveniences like lots and lots of extra variables, WITH blocks, extra "this" statements. They all add space and time in AS3 even though most other languages would compile down equivalent statements to the same thing.

* Long package and class names get stored in the SWF -- interned strings in the constant pool are a large percentage of SWF size.

* Keep lazy initialization of datastructures to a minimum (e.g. if (!foo) foo = new Foo() versus private var foo:Foo = new Foo()) -- class init and static init code is smaller and only runs once. The only advantages to lazy init are for data structures that are expensive to keep around if not being used, and/or you will null them periodically.

* Function arguments and local variables are cheapest to use because AS3 doesn't have to search up the scope chain when you access them. Global statics are awesome -- though caching their values locally is best if you're going to reference them a lot. Deep lookups like foo.bar.baz.getterFunction() are expensive if you're going to do a lot of work in baz -- try caching foo.bar.baz first.

* Anonymous functions: Don't get me started ;) See this post.

* If you use Flex, grep -r validateNow -- and eliminate them unless absolutely necessary. And if you don't remove it, leave a paragraph on why it must be there.

* Getter functions cost more than versus get() functions; and they often have hidden side effects. Don't write a getter unless that's all it does, and in constant time.

* Mark ever variable as const unless you need it to be variable. One day there may be a performance benefit, like finals in Java. But until then, bask in one fewer category of bugs.

* If you're embedding gobs of XML (damned if I know why you'd need to do this): Pasting the XML into a class as a static XML object offers the best performance and compression. The compile-time processing and optimization is significant versus runtime parsing, type checking, and decompression in a ByteArray (if you compressed it on the wire)

JITing in the Flash VM

Three things that came to mind recently:

* Constructors should be as short and fast as possible -- don't do any computation in them. Flash never JITs the constructor function, it's always fully interpreted. (There are performance tests to show this, though I know it for fact.) If you must do some work in the constructor, or the constructor will get called often (e.g. not a Singleton) -- write a private function to do the work and call it from the constructor.

* If you are using an Array and indexing it numerically (i.e. not an associative array -- one that uses string indexes), you can improve access speed to the array by hinting as follows:
Even if idx is already an int, the type coercion sends a hint to the JIT.

* Finally, not so important, but in tight loops or ones with many iterations: Best practice is to cache the length of an array to a const rather than inlining it.

It's been suggested to me that iterating over Arrays backwards is faster (and you can save a lookup by simply decrementing the index each iteration until it is -1 rather than testing for equality against the length). Though it very well might a) not be true b) be JIT/platform-dependent. It's confusing as hell, so I'd only suggest doing that if you're already doing something impossible-to-understand like dynamic programming or have shown benefits on at least one platform.