Custom Search

Thursday, August 20, 2009

Need to optimize flash 9

I've been using flash 8 and 9 for some simple Multi touch drawing board application and realised that it is running too slow and requires a very fast computer to run it. Therefore, the need to optimize the code. I quick search on the internet led me to the following tips:

1) Declare local variables instead of global variables. (i had the impression that global variables just take up ram but will run faster during runtime. But i guess i'm wrong)
function doSomething() { var mx = 100 var my = 100 var ar = new Array()...}

2) Using OnEnterFrame, it is not recomended to attach too many event handlers all over the movie clip because this can lead to spaghetti code and also it can significantly degrade performance.
Most of the times using one single onEnterFrame can be a good solution: just one main loop that takes care of the various operations to carry on.

3) 25-35fps. The higher the fps the slower it will run the code.

4) Visibility. One of the best solutions to this problem is to have an empty frame in your movieclips where you can gotoAndStop(), freeing up some work to the flash player.
_visible = false; doesn't work.

5) for in loop instead of the usual for or while syntax.
for (var i in arr) {  if (arr[i] > 50)  {   // do some processing here  } } 
is faster than 
for (var i=0; i<10000;> 50)  {   // do some processing here  } } 
//------------------------------------------------------------------------
var i=-1 while (++i <>
is faster than 
for (var i=0; i<1000;>
//-----------------------------------------
6) _global vars is faster than Timeline vars. 
7) Multiple var declaration is faster than single
8) Var name lookup
t = getTimer() var floor = Math.floor var ceil  = Math.ceil for (var i=0; i < num =" floor(MAX)">
is better than 
for (var i=0; i < num =" Math.floor(MAX)">
9) Short var names is better than long variable names
10) Declaring var in loops (to the contrary) is faster than declaring before a loop.
11) using single if statements is faster than complex conditional expressions in a single if statement.
12) Nested loops, while loop is faster than for loops (eg for 2D data) 
13) TellTarget vs dot syntax. 
tellTarget(mc){
_x =10;
_y = 10
} 
is faster than mc._x = 10; mc._y = 10;
14) Loop listening for pressed keys
if(Key.isDown(Key.LEFT)) 
use 
keyDown = Key.isDown
if(keyDown){}
instead. 
15) use int() instead of Math.Floor()
16) Often performance is about perception.
If you attempt to perform too much work in a single frame, 
Flash doesn't have time to render the Stage, 
and the user perceives a slowdown. 
If you break up the amount of work being performed into smaller chunks, 
Flash can refresh the Stage at the prescribed frame rate, 
and there is no perceived slowdown.
16) loads more at this forum: 
http://board.flashkit.com/
http://flasm.sourceforge.net/
The Flashkit Board Optimization thread
Bit-101 Forum Optimizations Tips
OddHammer Tips

No comments: