Effective ActionScript: variable testing

Uncategorized, JavaScript, ActionScript, Front-End Programming — Matas Petrikas on March 28, 2007 at 2:01 pm
It’s a pretty usual ActionScript code excerpt:
 if (variable == true){ doSomething(); }
as you can see, the variable value is being tested here against its true value, which is a totally redundant action. A much more convenient style would be:
 if (variable){ doSomething(); }
What so nice about this solution, that it can check any variable types for valid values. Both following tests work identically :
 
var variable:Number = null;
if (variable){ doSomething(); }
 
var variable:String = undefined;
if (variable){ doSomething(); }

Effective ActionScript: Iteration

Flash, ActionScript, Front-End Programming — Matas Petrikas on March 27, 2007 at 3:12 pm
This post was inspired by Volodja Kolesnikovs article about non-trivial syntax in JavaScript. ActionScript and JS are both ECMA languages, which is why these ideas could be aplied to AS programming too. Take for example a “for” loop iteration. Here is a very usual example:
for(var i = 0; i < array.length; i++){
// here comes iteration code
}
The problem is, it calls the array length every cycle, thus wasting CPU resources. A better soulution would be:
var arrLength:Number = array.length;
for(var i = 0; i < arrLength; i++){
// here comes iteration code
}
We’ve called array.length just once here, but also we’ve created a variable, which has probably no use outside of iteration loop. The prettier and more effective solution would be:
 
for (var i = 0, l = myArr.length; i < l; i++) {
// here comes iteration code
}
We’ve saved some CPU cycles, and packed all iteration code in one compact piece. I’ve rewritten Volodjas test script in AS so you could check it for yourself. It looks, that you can save up to 60-70% CPU cycles using the effective method. iteration_test.as

How many times have I…

(X)HTML, Front-End Programming, Accessibility — Matas Petrikas on March 13, 2007 at 5:05 pm
Just a short notice: next time you have to write 2×2=4 or “2x faster!” in your code, use a HTML entity
times
(Unicode No: 215) instead of small cap X.
More semantics — better Karma!
This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 2.5 License. | Matas Ideas and Thoughts