Please note that ExpatTech no longer operates regular office hours, meeting is by appointment only. Please call +36306031104 for details.

ExpatTech Techblog

Peter Todd 2009.06.25. 13:33

Flash Cookbook - Optimisation - optimizing flash code Part 1.

This time we will go a bit deeper and see if flash code can be optimized (what a question!).

Of course it can be. We are not talking about single 1-2% optimization, but heavy stuff here.

Our frame code will be a counter and a cycle. For a million times we will run several algorithms, which in our case will give the same result - but not in the same time!

Let's see our code:

var array:Array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

var t_start:Number = getTimer();

for(var i:int = 0; i < 1000000; i++)
     for0();    
     //for1();
}

var t_stop:Number = getTimer();

trace(t_stop - t_start);

function for0():void
{
    for(var i:int = 0; i < array.length; i++)
    {
        var a:int = array[i];
    }
}

function for1():void
{
    var len:int = array.length;
   
    for(var i:int = 0; i < len; i++)
    {
        var a:int = array[i];
    }
}

As you can see we will measure the runtime of a simple for loop. In the first case we set the limit to array.length, second, we create a variable, calculate the length first, and put this as a constant value to the cycle.

We run both functions 9 times, and calculate the average and deviation.

Results of first algorithm:

1169
1168
1166
1166
1166
1167
1166
1167
1168

average: 1167, deviation: 1.05

Results of second algorithm:

414
412
418
416
418
413
414
414
413

average: 414.67, deviation: 2.05

AMAZING RESULTS! practically you can say that the second way is 2.81 times faster! That's something to consider. Your code needs 35.47% of the time to run!

I think this needs no further explanation. Furthermore, if you dig deeper and deeper, you will always find a way to dramatically optimize your flash code.