4k Game Contest – and a word about ternary operations in AS3
Edit: Thanks to Kevin Luck for pointing out a flaw with the code in my original post (there was an extra assignment taking place, which caused the byte count to increase). Remove that and ternary will match if/else on a bytes-used basis. I'll keep this post up here regardless, just ignore everything from this point on ![]()
Disinformation follows:
While working on my 4k Game Competition entry tonight, I found out something that may be useful for others entering:
ternary operations in AS3 will often result in a larger final SWF size.
Here is a set of if/else conditionals taken from the game I'm working on:
-
<br />
-
if (lx == 0)<br />
-
{<br />
-
this.x = Math.random() * 550;<br />
-
}<br />
-
else<br />
-
{<br />
-
this.x = lx;<br />
-
}</p>
-
<p>if (ly == 0)<br />
-
{<br />
-
this.y = Math.random() * 400;<br />
-
}<br />
-
else<br />
-
{<br />
-
this.y = ly;<br />
-
}<br />
I replaced the above with this:
-
<br />
-
x = (lx == 0) ? x = Math.random() * 550 : x = lx;<br />
-
y = (ly == 0) ? y = Math.random() * 400 : y = ly;<br />
Much more compact, 15 lines less code, does exactly the same thing as the unrolled version above it - yet it uses 20 more bytes in the final SWF. Blindly use ternary operations around your whole 4k game and suddenly you could be wasting a large amount of bytes when you think you're saving them (because you're entering less code).
There are a few other little tricks I've found while coding this game, and they pretty much all lead back to the same rule: for a smaller SWF size, unroll everything. When 4096 bytes is all you have to play with, this can make all the difference.
Tags: 4k game competition, optimisation






February 18th, 2009 at 1:19 am
How about this?
x = lx || Math.random() * 550;
y = ly || Math.random() * 400;
I’d be interested to know if it came out smaller or not… It certainly looks smaller…
Cheers,
Kelvin
February 18th, 2009 at 1:23 am
btw, your ternary examples should probably be:
x = (lx == 0) ? Math.random() * 550 : lx;
y = (ly == 0) ? Math.random() * 550 : ly;
The extra assignments might explain the extra bytes…
Cheers,
Kelvin
February 18th, 2009 at 1:24 am
Sorry – last comment I promise! Should be * 400 in the second line of the example above, not * 550…
February 18th, 2009 at 2:02 am
Ahh yes, it was the extra assignment causing the increase in size.
However, your first version trumped the ternary by quite some margin – saving an extra 6 bytes in total