« Tips on how to write efficient AS3 - part 2»

robot-calculatorAs a continuation from my last post regarding AS3 and performance here are some more tips I found interesting.

Array push vs. Array index

Don’t use the push function on an Array instead use the Array length property and set on the Array like so list[list.length] = data; Or if that’s not enough for the best performance (about 600% faster) than using push don’t use the Array length property at all. To do this keep the Array length as an external variable and increment/decrement it as you add and remove items from the Array.

Array emptying - length 0 vs. A new Array

If you need to empty an Array there is a handy option to do this via setting the Arrays property length to 0. You would think this would be the better option as you are avoiding creating a new Array and ultimately saving memory. Though it’s interesting to know as a trade off using length to clear an Array is not faster in performance (in most cases). Using length is more efficient when you might need to clear more than 510 Arrays in a single execution, otherwise creating a new Array via [] is the faster option again.

Var declarations on multiple lines vs. Var declarations on a single line

If you need to declare a few variables it’s slightly more efficient to do so on a single line i.e.
var a:int=0, b:int=0, c:int=0;
vs.
var a:int=0;
var b:int=0;
var c:int=0;

Using Xor to swap variables

Using Xor is very handy if you want to swap variables but don’t want to create a third variable i.e.

a = a^b;
b = a^b;
a = a^b;

Like most people I thought this would be more efficient but it’s not compared to creating a third variable and then doing the swap. In fact it’s about 300% more efficient to do the swap this way. Though honestly I still have a soft spot for the Xor method.

var oldB:int = b;
b = a;
a = oldB;

Multiplication vs. Division

When working with Math in Actionscript multiplications seem to always run faster than divisions so instead of 5000/1000 use 5000*0.001 it’s about 130% faster.

Type casting comparison

When type casting the keyword as is 250% more efficient than casting by Type(item); Though surprisingly not using either is about 1400% more efficient.

Long vs Short variable names

Though this one is debatable because it results in illegible code. Shortened variable names do give a millisecond or so improvement if iterating many 1,000’s of times in a single loop. Though I think this is a last resort in code optimization as the differences are really marginal.