March 17th, 2007
I’ve long been mildly obsessed with getting power out of Actionscript. These days Actionscript is fast enough that I can code with less time spent optimizing, but I still like writing code I know is faster than its more readable counterpart. I never thought this line, one I use frequently, would ever be trumped…
var value = obj ? obj : (obj = new Something());
It’s very straightforward, right? If obj doesn’t exist, it is created, and a non-null value of obj is always passed on. How could it get any better?
var value = obj || (obj = new Something());
That’s how. I spotted a similar line while checking out Papervision’s source code, the only library I’ve ever seen where the obsession with optimization is greater than my own. This line only offers one less operation, which is practically nothing, but it’s still very interesting especially when there could be real advantages to using them in a long series. You can do similar tricks with a
&& operator. These two lines do the basically same thing…
var value = objA ? objB : null;
var value = objA && objB;
A series of
&& operators returns the last statement if all previous statements are non-null. A series of
|| operators returns the first non-null statement. I always thought those operations converted everything into boolean values, but they don’t, they pass on values based on their equivalent boolean values. But that’s not all the interesting things I’m leeching from Papervision, there’s also the best lazy array iterator I wish I thought of…
var p, i = list.length;
while (p = list[--i]) p.doSomething();
var p, i = 0;
while (p = list[i++]) p.doSomething();
This line reminds me of my speed-obsessed days. It’s similar to a technique I’m using now, but it has a flaw (feature?). If the list changes then entries may be skipped or run more than once. Regardless, it’s very stable and probably the best way to handle things as long as an entry can be run twice or skipped without messing up everything. It probably doesn’t have a speed advantage over this… (Update: Looks like the following method is slightly faster as long as you don’t need to access
list[i] more than once)
var i = list.length;
while (i-- > 0) list[i].doSomething();
But it stores
list[i] in a variable, which allows static typing to be used, and makes sure the variable is non-null beforehand. Too cool.
Update: Did some basic speed tests. Papervision’s method beats out a “for each” loop every time. The “while (i –> 0)” loop has an advantage as long as
list[i] is accessed only once. Might just be my computer though.