Welcome to the RaidenX Official Site!
[ Home | New Features | Basics | Items | Cheats | Tutorials | Contact ]
Sorry about this plain design - I'll get the Flash version uploaded as soon as I could bother.

This tutorial is written specifically for Actionscript 2.0. If your Flash is a biggie with 3D renderings, API or multiplayer with lots going on at once, optimising the code could make all the difference. Remember we love our actionscript. :)

Time tests were done with Flash Player 8 on my computer and averaged out. Assuming they are proportional to yours, I gave relative results (how long the faster code takes if the slower code takes 100 sec) rather than the exact times they took for me.




1. Local Variables (Part I)
Use the keyword 'var' when a variable can do with being local.

'Var' is used to define local variables. These are faster to access and are removed once the function is complete.

// SLOWER - 100 sec
function operate() {
a = 0;
b
= 5;
while (++a < 30) {
b += random(a);
}
return b;
}
function onEnterFrame() {
operate();
}


// FASTER - 24 sec
function operate() {
var a:Number = 0;
var b:Number
= 5;
while (++a < 30) {
b += random(a);
}
return b;
}
function onEnterFrame() {
operate();
}



2. Local Variables (Part II)
Localise non-localised variables.

If a function makes reference to the same non-local variable more than 2 times, it is faster to localise it at the start, using "var." Speed increase will be more significant depending on how many times the non-local variable is called.

In the following example, 'foreign' is the non-local variable, which appears 5 times within the function.

foreign = 5;

// SLOWER - 100 sec
function operate() {
a =
foreign + 3;
b =
foreign - 3;
c =
foreign * 3;
d =
foreign / 3;
e =
foreign % 3;
}
function onEnterFrame() {
operate();
}

// FASTER - 47 sec
function operate() {
var local:Number = foreign;
a = local + 3;
b = local - 3;
c = local * 3;
d = local / 3;
e = local % 3;
}
function onEnterFrame() {
operate();
}




3. Loops and Iterations (Part I)
'For..in' and 'do..while' are better than 'for' and 'while.'

Here are array-loop comparisons: for, while, do..while and for..in.

a = [ 1, 2, 3, 4, 5 ];
b = 0;


// SLOWEST - 100 sec

for (i=0; i < a.length; i++) {
b += i;
}

// SLOW - 95 sec
var i:Number = -1;
while (++i < a.length) {

b += i;
}

// FAST - 88 sec
var i:Number = 0;
do {

b += i;
} while (++i < a.length);

// FASTEST - 82 sec
for (i in a) {
b += i;
}



Of course, you can't use for..in with other types of loops, so do..while is a close second.

** Special thanks to Inglor for suggesting do..while! **



4. Loops and Iterations (Part II)
Do all the required processing before the loop.

Times will vary depending on how many iterations there are. Pre-processing stops the same calculations from repeating over and over until the loop is done.

a = [ ];
var i:Number = 0;


// SLOWER - 100 sec

do {
a[i] = (
Math.PI / 180 + i) * (Math.pow(Math.E, Math.PI) + i) * i;
} while (++i < 100000);


// FASTER - 85 sec

var rad:Number = Math.PI / 180;
var epi:Number = Math.pow(Math.E, Math.PI);

do {
a[i] = (
rad + i) * (epi + i) * i;
} while (++i < 100000);




5. Misuse of Loops
Don't use loops when you don't have to.

Typing out a set of calculations is faster than using a loop which does those calculations. Don't be lazy! Flash isn't efficient with loops.

a = 3;

// SLOWER - 100 sec

var i:Number = 2;
do {
a *= i;
} while (++i < 10);


// FASTER - 12 sec
a
*= 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9;

// EVEN FASTER - 7 sec
a = 1088640;



6. Misuse of Functions
Don't use functions when you don't have to.

Functions are mostly used for repeating the same set of commands listed over and over (which saves time and space). You shouldn't use them for commands only listed once, because Flash recompiles the function each time it is called - waste of time.

function abc() {
var a:Number = 1;
b += a, c *= b;
}


// SLOWER - 100 sec

function onEnterFrame() {
abc();
}


// FASTER - 35 sec
function onEnterFrame() {
var a:Number = 1;
b += a, c *= b;

}


** Special thanks to TobyF for suggesting this idea! **



7. Misuse of LocalToGlobal/GlobalToLocal
Don't be lazy and write your own formula.

I won't dwell on about this topic - it seems obvious enough. Only use localToGlobal or globalToLocal as a last resort because they're untidy and slow. Here's a common one - finding a movie clip's global coordinates with localToGlobal when its parent clip has undergo no transformations other than moving.

// SLOWER - 100 sec
var pt:Object = { x:_x, y:_y };
_parent.localToGlobal(pt);
xglob = pt.x;
yglob = pt.y;

// FASTER - 38 sec
xglob = _parent._x + _x;
yglob = _parent._y + _y;



8. Misuse of 'This'
This isn't cool!

What 'this' does is create an extra lookup requiring more processing time. Using it when you don't have to is a waste of time, space and computer power.

// SLOWER - 100 sec
this.onEnterFrame = function() {
this._x += 5;
this._y += 5;
this._alpha -= 2;
this.a = 5;
this.o = { };
this.gotoAndStop(1);
};


// FASTER - 86 sec
onEnterFrame = function() {
_x += 5;
_y += 5;
_alpha -= 2;
a = 5;
o = { };
gotoAndStop(1);
};



9. Misuse of OnEnterFrame (Part I)
Not cool either!

I can't do any fair tests here, but try making sure that calculations are done when most appropiate, e.g. onMouseMove for cursors and onKeyDown for key-presses are good alternatives for onEnterFrame.

// SLOWER
function onEnterFrame() {
_x = _root._xmouse;
_y = _root._ymouse;
}


// FASTER
function onMouseMove() {
_x = _root._xmouse;
_y = _root._ymouse;
}



10. Misuse of OnEnterFrame (Part II)
Use setInterval... setInerval(function, mms_delay) - it's much better!


We could even survive without onEnterFrame. There's a better way called setInterval(), and not only is it faster, it also gives us more control over the frame rate. If you use setInterval, the initial frame rate of the movie could be set to 120fps to enhance smoothness and performance. The actual rate is up to you.

I recommend having around 25fps for movements - setInterval(movement, 40), and anything down to 1fps for progress cookie saves - setInterval(save, 1000). Saving once per second is better than saving 25 times per second.

In the following example, the number of frames elapsed were counted before one second is elapsed. The movie's initial rate is 120fps.

tm = 0;

// SLOWER - 124 fps (+3.33%)

function onEnterFrame() {
getTimer() < 1000 ? tm++ : trace(tm);
}


// FASTER - 982 fps (+718%)
(io = {}).nt = function() {
getTimer() < 1000 ? tm++ : trace(tm);
};
setInterval(io, "nt", 0);



11. Break
Kill the loop as soon as it's done its job.

'Break' could be used to end a loop - regardless whether it's finished or not - saving precious time (especially if the remaining calculations are unnecessary).

a = new Array(250), a[125] = true;
i = 0;


// SLOWER - 100 sec
do {
if (a[i] && !b) {
b = a[i];
}
} while (++i < 250);


// FASTER - 50 sec
do {
if (a[i] && !b) {
b = a[i];
break;
}
} while (++i < 250);


Times will vary depending on how soon the loop is ended. On the example above, 'break' is called when the loop is half-completed, so the time taken is halved.




12. Key/Math (etc) Functions
Create reference for lookups.

Creating variables for function lookups (or pre-calculations) save a lot of time, so Flash has less functions and calculations to do during runtime. 

keydown = Key.isDown;
log = Math.log;
sin = Math.sin;
rad = Math.PI / 180;


// SLOWER - 100 sec
function onEnterFrame() {
a =
Key.isDown(Key.SPACE) * 5;
b = Math.log(a);
c = Math.floor(b);
d = Math.sin(c * Math.PI / 180);
e = Math.log(a) * Math.floor(b);
}


// FASTER - 48 sec
function onEnterFrame() {
a =
keydown(Key.SPACE) * 5;
b = log(a);
c = int(b);
d = sin(c * rad);
e = b * c;
}


Notice that int() is faster than Math.floor() because it doesn't require any lookups. However, Math.floor() rounds down, while int() chips off decimal values. Thus, Math.floor(-4.5) = -5 and int(-4.5) = -4.



13. Declaring Functions
Use the faster syntax.

I was surprised at the big speed difference~!

// SLOWER - 100 sec
onEnterFrame = function() {
/* stuff */
};


// FASTER - 15 sec
function onEnterFrame() {
/* stuff */
}


In fact, using the second method to declare multiple functions shows hardly any time difference, whereas using the first causes the time to increase constantly.




14. Memory vs. Speed
Speed is more crucial!

The average computer we get nowadays have around 512MB of RAM, which is way more than enough to store thousands of variables. Deleting a variable saves memory (but you have lots of it anyway) in return for speed loss, so it's your call.

a = 5;

// SLOWER - 100 sec

b = a + 8;
delete a;

// FASTER - 64 sec
b = a + 8;


You won't even need to use "delete" for local variables so using those could save memory if you really have to.

Deleting only comes in handy for no-longer needed functions that continue to process (e.g. onEnterFrame) because it stops Flash doing calculations that are of no use.



15. GetBounds vs. HitTest
HitTest is a lot faster!

Well obviously, hitTest is better for bounding box collisions because that's basically what it does. Using getBounds will then require comparison of both objects' xMin to xMax and yMin to yMax which is of course, much slower.

// SLOWER - 100 sec
var a:Number = object1.getBounds();
var b:Number = object2.getBounds();
var x1:Number = object1._x;
var y1:Number = object1._y;
var x2:Number = object2._x;
var y2:Number = object2._y;
if (a.xMin + x1 < b.xMax + x2 && a.xMax + x1 > b.xMin + x2) {
if (a.yMin + y1 < b.yMax + y2 && a.yMax + y1 > b.yMin + y2) {

/* hitTest is true */
}
}


// FASTER - 23 sec
if (object1.hitTest(object2)) {
/* hitTest is true */
}


Times may vary depending on the shapes of both movie clips. Still it is obvious that hitTest is a lot faster for bounding box collision. Use getBounds only if necessary.




16. Operators vs. HitTest (Part I)
Err hitTest again?

I'll focus on circular and rectangular collision as those are most common. Assuming you want to collision-detect an irregular object (e.g. top-down fighter jet), either one is fine. Circular detection is slower because we have to write our own formula in actionscript. While Flash was programmed in C, hitTest is sure to run faster.

// SLOWER - 100 sec
var xdist:Number = object1._x - object2._x;
var ydist:Number = object1._y - object2._y;
var rad1:Number = (object1._width + object1._height) / Math.PI;
var rad2:Number = (object2._width + object2._height) / Math.PI;
if (xdist * xdist + ydist * ydist < rad1 * rad1 + rad2 * rad2) {

/* hitTest is true */
}

// FASTER - 40 sec
if (object1.hitTest(object2)) {
/* hitTest is true */
}



17. Operators vs. HitTest (Part II)
Yay hitTest!

Now for rectangular collision. Drawing a rectangle or bounding box around the two objects is basically what hitTest does, but we'll use a written formula to compare. Same concept applies - formulas written in actionscript aren't as effective.

// SLOWER - 100 sec
var x1:Number = object1._x;
var y1:Number = object1._y;
var x2:Number = object2._x;
var y2:Number = object2._y;
var w1:Number = object1._width / 2;
var h1:Number = object1._height / 2;
var w2:Number = object2._width / 2;
var h2:Number = object2._height / 2;
if (x1 - w1 < x2 + w2 && x1 + w1 > x2 - w2 && y1 - h1 < y2 + h2 && y1 + h1 > y2 - h2) {

/* hitTest is true */
}

// FASTER - 40 sec
if (object1.hitTest(object2)) {
/* hitTest is true */
}




18. Shape Flag vs. HitTest
HitTest wins again.

Shape flags and hitTests do different things, but in a situation where either of them are good, stick to hitTest. HitTest only finds bounding boxes - not the entire shape.

// SLOWER - 100 sec
if (a.hitTest(b._x, b._y, true)) {
/* hitTest is true */
}

// FASTER - 74 sec
if (a.hitTest(b)) {
/* hitTest is true */
}



Seriously, I don't think hitTest (without shape flag) is 'slow' compared to other collision methods, as many people may think it is.



19. Creating Arrays
Array access operator.

Treat arrays like arrays, not a container with loads of variables.

// SLOWER - 100 sec
a = new Array();
a[0] = 0;
a[1] = 1;
a[2] = 2;
a[3] = 3;
a[4] = 4;
a[5] = 5;
a[6] = 6;
a[7] = 7;


// FASTER - 84 sec
a = new Array( 0, 1, 2, 3, 4, 5, 6, 7 );

// EVEN FASTER - 65 sec
a = [ 0, 1, 2, 3, 4, 5, 6, 7 ];



20. Creating Objects
Object initialiser.

Same concept as creating arrays.

// SLOWER - 100 sec
initObject =
new Object();
initObject._x =
50;
initObject._y =
100;
initObject._rotation =
180;
initObject.a =
1;
initObject.b =
2;
initObject.c =
3;

// FASTER - 59 sec
initObject =
{ _x:50, _y:100, _rotation:180, a:1, b:2, c:3 };



21. Updating Object Variables
Don't get this and the tutorial above mixed up!

Declaring variables in an (already defined) object using { } actually takes longer, because it replaces the object with a brand new one each time.

initObject = { };

// SLOWER - 100 sec
initObject = { _x:50, _y:100, _rotation:180, a:1, b:2, c:3 };

// FASTER - 65 sec
initObject._x =
50;
initObject._y =
100;
initObject._rotation =
180;
initObject.a =
1;
initObject.b =
2;
initObject.c =
3;



22. AttachMovie
The most useful way of attaching movie clips - so do it fast!

Here is an example of a common slow way of doing it, compared to the fastest I could make it as.

// SLOWER - 100 sec
initObject = new Object();
initObject._x = 30;
initObject._y = 40;
initObject._rotation = 50;

attachMovie("clip", "clip"+getNextHighestDepth(), getNextHighestDepth(), initObject);

// FASTER - 60 sec
attachMovie("clip", "", getNextHighestDepth(), { _x:30, _y:40, _rotation:50 });



23. Attaching Movie Clips
DuplicateMovieClip appears to be faster.

... as long as you use the faster syntax. Depending on the graphics of the attached clip, the speeds of attachMovie and duplicateMovieClip may vary. In the following examples, an empty movie clip with instance name "empty" and linkage identifier "blank" is placed on stage, so all four scripts do practically the same thing.

// SLOWEST - 100 sec
empty.duplicateMovieClip(id, id);

// SLOW - 95 sec
attachMovie("blank", id, id);

// FAST - 88 sec
createEmptyMovieClip(id, id);

// FASTEST - 74 sec
duplicateMovieClip(empty, id, id);



24. Removing Movie Clips
Use the faster syntax.

Dot notation is the winner here.

// SLOWER - 100 sec
removeMovieClip(a);

// FASTER - 63 sec
a.removeMovieClip();


This also applies to like actions such as - this.startDrag() not startDrag(this).




25. Decimals vs. Fractions
Flash prefers fractions!

I've tested it a few times - division assignment with integers is always better than multiplication assignment with decimals.

a = random(8);

// SLOWER - 100 sec
a *= .5;

// FASTER - 97 sec
a /= 2;


We still know that integers are faster than decimals, and multiplication assignment is faster than division assignment. Let this be a reminder.

** Special thanks to ColdLogic for thinking multiplication is always faster. :P **



26. Mathematical Operators
To be used wisely.

When writing formulas and math-related stuff in Flash, try using operators over functions, and numbers over variables.

xdif = 75;
ydif = 100;
radius = 750;
i = 4;
j = 8;
k = 12;


// SLOWER - 100 sec
if (Math.sqrt(xdif * xdif + ydif * ydif) < radius) {
a =
i + i + i + i;
b =
Math.pow(j, 3);
c =
Math.pow(k, 0.5);
}


// FASTER - 78 sec
if (xdif * xdif + ydif * ydif < radius * radius) {
a =
i * 4;
b =
j * j * j;
c =
Math.sqrt(k);
}


Note that Math.sqrt(x) is faster than Math.pow(x, 0.5).



27. Mathematical Assignments
Use them if you can - they do speed things up.

Assignments reduce the amount of variables in an equation, so Flash has less recompiling to do (which speeds things up right?).

a = random(16);
b = random(16);
c = random(16);
d = false;
e = random(16) * Math.E;


// SLOWER - 100 sec
a = a + 3;
b =
b / 5;
c =
c + 1;
d =
c < 12 ? true : false;
e =
Math.pow(2, 13) * e;

// FASTER - 85 sec
a += 3;
b
/= 5;
d =
++c < 12;
e
<<= 13;


As a side note, x++ is faster than x += 1 in Actionscript 2.0 but it's the other way round in Actionscript 3.0 (same for decrement).



28. Mathematical Simplification
As in the algebra way.

Brackets. Only use them if they help shorten your code (i.e. less variable calls).

a = random(24);
b = random(24);
c = random(24);


// SLOWER - 100 sec

a = b - (-1);
c =
c * a + c * b + c * c;

// FASTER - 67 sec
a = b + 1;
c =
c * (a + b + c);



29. IF vs. Min/Max
IF takes longer to write, but worth it.

I think they kinda messed up coding the min/max functions. IFs are the way to go.

speed = 0;
min = Math.min;


// SLOWER - 100 sec

function onEnterFrame() {
if ((speed += 5) > 50) {
speed = 50;
}
}

// FASTER - 78 sec
function onEnterFrame() {
speed =
min(speed + 5, 50);
}



Well, that's the case where you want to keep speed from topping over 50. If you want a simple comparison: a = b > c ? b : c is definitely faster than a = Math.max(b, c).

** Special thanks to TobyF for suggesting this idea! **



30. IF vs. Conditional (Part I)
Conditional for the basic if/else.

Let's say you want a clean one-to-one if/else statement, then conditional is a bit faster (I recommend you use it - it's neat how everything is squashed into one line).

b = random(4) + 1;

// SLOWER - 100 sec

if (b >= 3) {
a = 3;
} else {
a = 2;
}


// FASTER - 94 sec
a = b >= 3 ? 3 : 2;



31. IF vs. Conditional (Part II)
IF for more advanced statements.

More advanced stuff like nested statements, IF is definitely faster:

angle = Math.random() * 1440 - 720;

// SLOWER - 100 sec

angle += angle < 0 ? 360 : (angle >= 360 ? -360 : 0);

// FASTER - 68 sec
if (angle < 0) {
angle += 360;
} else if (
angle >= 360) {
angle -= 360;
}




32. IF vs. Switch
Good substitute for ongoing IF statements.

Whenever you want to have an IF statement followed by a bunch of ELSE IFs that test the value of the same variable, let's say you ain't cool unless you SWITCH. Try to put in conditions that are more likely to happen first, because the earlier the condition is, the more calculations Flash could skip afterwards.

a = random(7);

// SLOWER - 100 sec

if (a == 1) {
b = 1;
} else if (
a == 2) {
c = 1;
} else if (
a == 3) {
d = 1;
} else if (
a == 4) {
e = 1;
} else if (
a == 4) {
f = 1;
} else if (
a == 5) {
g = 1;
} else if (
a == 6) {
h = 1;
} else {
a = 1;
}


// FASTER - 61 sec
switch (a) {
case
1 :
b = 1;
break;
case
2 :
c = 1;
break;
case
3 :
d = 1;
break;
case
4 :
e = 1;
break;
case
5 :
f = 1;
break;
case
6 :
g = 1;
break;
case
7 :
h = 1;
break;
default :
a = 1;
}



But if you have only have a single ELSE statement, IF is a bit faster. I suggest you use conditionals for that though, because that's even faster than IF.

** Special thanks to Muttski for suggesting this idea! **



33. Long vs. Short
Long variable names require more processing.

What's the point?

// SLOWER - 100 sec
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa = 1;
bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb = 2;
kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk = 3;

// FASTER - 81 sec
a = 1;
b = 2;
k = 3;


My recommendation is 1-3 letters. Feel free to use more when writing a tutorial or asking for help - that's when you need to make things clear. If you really need to write long variables, software like the ASO Obfuscator could rename the variables of your SWFs.




34. Equality Operator
Operates faster in a row.

For a different set of variables to equal the same thing, chain them all into one line of equal signs. Fair speed difference - and saves room as well.

// SLOWER - 100 sec
a = 3, b = 3, c = 3, x = 3, y = 3, z = 3;
f.onPress = function() {
this.startDrag();
};
g.onPress = function() {
this.startDrag();
};
h.onPress = function() {
this.startDrag();
};

// FASTER - 57 sec
a = b = c = x = y = z = 3;
f.onPress = g.onPress = h.onPress = function() {
this.startDrag();
};



35. On-Spot Operating
As with the tutorial above, one line is faster.

Basically the same concept. Reducing the number of variable calls increases the flow of your script. But remember your brackets!

a = b = c = d = 4;

// SLOWER - 100 sec

a += c;
b += d;

if (
a > b) {
// stuff
}

// FASTER - 87 sec
if (
(a += c) > (b += d)) {
// stuff
}



36. Operators vs. Logic Gates
Use NOT instead of STRICT EQUALITY.

NOT (!x) is quicker at finding if x is equal to 0 than STRICT EQUALITY (x == 0). As for testing if x is not equal to zero (x !== 0), it is faster to test if x is true (x). Remember, when x = 0, x is also considered 'false,' and if it's any other number, x is also considered 'true' (for non-strict equality use only).

a = b = c = 0;
d = false;


// SLOWER - 100 sec

if (a == 0) {
/* stuff */
}
if (b
!== 0) {
/* stuff */
}
if (c
< 0 || c > 0) {
/* stuff */
}
if (d
== true) {
/* stuff */
}


// FASTER - 67 sec
if (!a) {
/* stuff */
}
if (b) {
/* stuff */
}
if (
!c) {
/* stuff */
}
if (d) {
/* stuff */
}

// FASTEST - 64 sec
if (a) {
} else {

/* stuff */
}
if (b) {
/* stuff */
}
if (c) {
} else {

/* stuff */
}
if (d) {
/* stuff */
}

Since testing for true is faster than testing for false, always test for true. Even if you need to test for false, still test for true but use the "else" complimentary and put your statements there (as shown by the last example above, for variables a and c).

It doesn't matter if there's nothing under the actual "if," as long as the statements are under "else," testing for false is equally as quick as testing for true.




37. Declaring Boolean Values
IF for the lose - definitely this time!

Although mentioned briefly on the "Mathematical Assignments" tip, here it is again - treating inequalities as true/false makes things faster.

a = random(10);

// SLOW - 100
sec

if (a < 5) {
b
= true;
} else {
b
= false;
}

// FAST - 98 sec
b
= a < 5 ? true : false;

// FASTEST - 96 sec
b
= a < 5;



38. Testing Boolean Values
IF statements over equations.

Treating Boolean values as numbers is less efficient because Flash has to convert true or false into 1 or 0 then do a calculation, while finding if something is actually true or false does the whole thing straight away.

// SLOWER - 100 sec
if (released
* (Key.isDown(Key.SPACE) + Key.isDown(Key.ENTER)) > 0) {
/* stuff */
}
a += Key.isDown(Key.UP)
* 40;

// FASTER - 75 sec
if (released
&& (Key.isDown(Key.SPACE) || Key.isDown(Key.ENTER))) {
/* stuff */
}
if (Key.isDown(Key.UP)) {
a += 40;
}



39. Converting Variables to Strings
With the exception of arrays, add a "" at the end.

Besides using variable.toString(), adding a nothing-string ("") is the fastest way to do this. Unless the variable is an array, which we'll discuss on the next section.

a = 1234567890;

// SLOWER - 100 sec
a
= a.toString();

// FASTER - 31 sec
a
+= "";



40. Converting Arrays to Strings
Join() function is the fastest.

For arrays, adding "" at the end is still faster than toString(), but array.join() is really the fastest of them all.

a = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ];

// SLOWER - 100 sec
a
= a.toString();

// FASTER - 34 sec
a
+= "";

// FASTEST - 29 sec
a
= a.join();



41. Converting Strings to Integers
Always use int().

If the string is a decimal, int() or parseInt() will cut off the decimal places and turn it into an integer. ParseFloat() does not remove decimals, so it takes longer.

a = 1234567890;

// SLOWER - 100 sec
a =
parseFloat(a);

// FASTER - 36 sec
a =
parseInt(a);

// FASTEST - 22 sec
a =
int(a);



42. How long is a piece of String?
Get rid of that dotty notation.

Use length(string) not string.length.

a = "ABCDEFG";

// SLOWER - 100 sec
b = a
.length;

// FASTER - 28 sec
b =
length(a);



43. Dot Notation vs. TellTarget
Old notation ain't here for nothing!

TellTarget is a tad quicker, despite its depreciation after teh dots were introduced. Flash 4 notation must run quick to not lag on the slow computers those days eh? Use tellTarget whenever you can!

// SLOWER - 100 sec
a._x = 40;
a._y = 20;
a.b = 5;
a.c = { };
a.d += a.b + a._x + a._y;
a.gotoAndStop(a.d);

// FASTER - 94 sec
tellTarget (a) {
_x = 40;
_y = 20;
b = 5;
c = { };
d += b + _x + _y;
gotoAndStop(d);
}



44. Timeline Control
Guess I'm bored now.

50 trials were taken and here are the average results. Use nextFrame() or prevFrame() if you want to reach an adjacent frame (who wouldn't!?).

// SLOWER - 100 sec
gotoAndStop(2);
gotoAndStop(1)
;

// FASTER - 99 sec
nextFrame();
prevFrame()
;



45. Filters vs. SetTransform
Flash 8 filters are a nightmare.

Okay we're getting a bit into graphics optimisation here... the filters (e.g. blur) introduced in Flash 8 require even more processing than alphas. I'm specifically targeting the 'adjust colour' option because there are alternative ways to do that too. That's where setRGB and setTransform come in. I'll focus on setTransform since I find it more useful.

// SLOWER - 100 sec
import flash.filters.ColorMatrixFilter;
filters = [ new ColorMatrixFilter( [
2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 1, 0 ] ) ];

// FASTER - 68 sec
new Color(this).setTransform( { ra:200, ga:200, ba:200 } );


The time values shown above are only the times taken for the codes to run (where setTransform already is a bit faster), and not how fast the rendered object will run afterwards. It should be clear that the setTransformed object is the faster one.




46. Version Check
Less classes/lookups the better.

GetVersion() runs faster than System.capabilities.version because of the lack of lookups, but I guess optimising is pointless because you rarely use it in a Flash movie anyway.

// SLOWER - 100 sec
ver = System.capabilities.version;

// FASTER - 90 sec
ver = getVersion();


Same concept applies to using random(x) instead of Math.floor(Math.random() * x), int() instead of Math.floor(), and many other like situations.




47. _root vs. _level
_root is easier for Flash to access.

Unless your Flash has other imported movies during runtime, I suggest you replace all _level or _level0 with _root. It does speed things up a teeny bit. Even with _root, Flash treats the variable inside _level0 (try tracing it).

// SLOWER - 100 sec
_level.a = 1;
_level.b = 2;
_level.c = 3;

// FASTER - 91 sec
_root.a = 1;
_root.b = 2;
_root.c = 3;




48. Other...
Not enough yet huh?

These were also tested but have no significant difference in performance. I suggest using the shorter equivalence though (like .5 instead of 0.5), as it could make things easier to read and of course, reduce file size.

1. External vs. internal:
onClipEvent(enterFrame) __vs.__ onEnterFrame=function()
2. Play vs. stop:
gotoAndPlay(3) __vs.__ gotoAndStop(3)
3. Comma vs. semi-colon to declare var: var a=1, b=2 __vs.__ var a=1; var b=2
4. Point vs. zero:
.25 __vs.__ 0.25
5. Include vs. exclude: <= __vs.__ <
6. Greater than vs. less than: > __vs.__ <
7. Inequalities: !== __vs.__ <>
8. Brackets vs. no brackets: (((((64))))) __vs.__ 64
9. Hexadecimal vs. decimal:
0xFFFFFF __vs.__ 16777215
10. Key vs. number:
Key.LEFT __vs.__ 37
11. Roundings:
Math.round(4.5) __vs.__ Math.floor(4.5) __vs.__ Math.ceil(4.5)
12. Variable declaration: a=true __vs.__ var a=true __vs.__ var a:Boolean=true
13. HitTest complexity order:
line.hitTest(scribbles) __vs.__ scribbles.hitTest(line)
14. Create movie clip syntax: this.createEmptyMovieClip __vs.__ createEmptyMovieClip
15. Commentry syntax:
/*COMMENT*/ __vs.__ //COMMENT
16. Number of gaps (empty lines) between each line of code




Anymore to suggest/ask about? I'd love to hear them! Contact me please. ;D

(C) Go0gley 2005-2006


Back to Top
Back to Tutorials MAIN

RaidenX is made by Go0gley and sponsored by CrazyMonkeyGames.com.
Raiden and Raiden II are trademarks of Seibu Kaihatsu.INC.
Our aim is to lure all shoot-em-up fans worldwide to RaidenIII, trademark of MOSS.

Free Domain Name - www.YOU.co.nr Download - Flash Player 7