Tips on how to write efficient AS3

robot-calculatorJust recently I have needed an in depth understanding of AS3 efficiency practises, so I figured this is easiest done by getting involved in a series of relevant tests. Though there are similar blog posts regarding this most have been focused on either loops or Number types and this article won't repeat these tests as I too discovered similar suggestions.

Here are my tests :

Array & Object constructing

new Array() and new Object() are about 3 times slower than [] and {}. Though further to this [] is much slower than [].concat() so if you have a constant reference to an empty Array use [].concat().

Index Number type for Arrays

In AS2 list[int(0)] was faster than list[0] this is no longer the true. list[0] is now the faster option. list[int(0)] is now faster than list[0]!

Create Array vs. Updating Array

If you can avoid it don't constantly create Arrays/Objects this is especially the case in long loops rather create them once then update.

Nulling Array vs. Splicing Array

When working with large Arrays splicing is obviously an expensive operation, you can avoid this by nulling the index and skipping it in a null scenario. If you need to splice in order to keep the Array length low. Then store these nulled indexes in another trash Array once the garbage count has reached a limit you've defined loop through the numerically sorted trash indexes deleting splices in bulk. This concept is demonstrated in Tweensy.

Nulling Object vs. Delete Object

Deleting an item in an Object is always more extensive than nulling it. If you're using a Dictionary try to use weak references in that case once the key is dereferenced the Flash garbage collector will eventually remove the item from the Dictionary.

Nesting Loops

Nesting loops is always slower try to minimize your nest depth to no more than 2. As well always use for loops if you can they are the fastest.

Inline code vs. function references

When executing a function it's more expensive if you call other functions within it, so if the function is an enterframe function or long loop try to minimize referencing alot of functions for best performance.

Arguments vs. variable referencing

Arguments in functions are slower than a reference to an objects variables so try to minimize the number of arguments you use.

Function apply scoping do it or not?

Scoping function.apply is a little bit slower than not so if you don't have to then don't.

Continue onto part 2