4k Game Contest – and a word about ternary operations in AS3

4k 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:

CODE:
  1. <br />
  2. if (lx == 0)<br />
  3. {<br />
  4.     this.x = Math.random() * 550;<br />
  5. }<br />
  6. else<br />
  7. {<br />
  8.     this.x = lx;<br />
  9. }</p>
  10. <p>if (ly == 0)<br />
  11. {<br />
  12.     this.y = Math.random() * 400;<br />
  13. }<br />
  14. else<br />
  15. {<br />
  16.     this.y = ly;<br />
  17. }<br />

I replaced the above with this:

CODE:
  1. <br />
  2. x = (lx == 0) ? x = Math.random() * 550 : x = lx;<br />
  3. 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.

Post to Twitter Post to Delicious Post to Digg Post to Facebook Post to Ping.fm Post to Reddit Post to StumbleUpon

Tags: ,

4 Responses to “4k Game Contest – and a word about ternary operations in AS3”

  1. Kelvin Luck Says:

    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 :)

  2. Kelvin Luck Says:

    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 :)

  3. Kelvin Luck Says:

    Sorry – last comment I promise! Should be * 400 in the second line of the example above, not * 550…

  4. rich Says:

    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 :)

Leave a Reply