I think that there are so many different compression tools and byte-saving techniques that the common programmer doesn’t know about that it can be a real detriment to them, and often a bit unfair. We’ve had threads like this one before, so I figured I’d start a new one.
Applet Templates
Start with a good applet template. It will have all the base functionality you need in the fewest bytes possible.
http://www.java-gaming.org/index.php/topic,21626.0.html
Compress your class
There are several ways you can do this. Riven has amazingly provided us with an HTTP service that does all the dirty work for you.
Compile 'n Shrink - HTTP Service - http://www.indiespot.net/app/java-four-kay
If you do not use Riven’s tool, then you should use Pack200 and at least one compression tool (maybe all of them!). This can be a bit time consuming but will save you a massive number of bytes.
Pack200
No matter how you do it, you will want your game to eventually be compressed with Pack200.
http://java.sun.com/j2se/1.5.0/docs/api/java/util/jar/Pack200.html
http://java.sun.com/j2se/1.5.0/docs/guide/deployment/deployment-guide/pack200.html
Compression Tools and Obfuscators
There are lots of different tools out there to squeeze a few extra bytes out of your jar. I will eventually include specific guides with how to use each tool as they are written.
ProGuard - http://proguard.sourceforge.net/
JShrink - http://www.e-t.com/jshrink.html
JoGa - http://www.nq4.de/
Smart Techniques
Note that a lot of these things will be automatically adjusted by most optimizers. Still isn’t it fun to do a lot of it manually?
- All global variables should be named only a single character. Local variables can have whatever name you want.
- All constants should be declared static final so they can go in the constants pool.
- In general, you should use the shortest possible method names you can, like System.nanoTime() versus System.currentTimeMillis().
- Every string literal you create adds at least a couple bytes per character. As a result, keep your strings short.
- Every time you use a method, it will add bytes equal to the number of characters in that method. However, each method will be added only once for all uses.
- Keep your code all in one class, and put all your code in one Applet method (like start()).
- Use local variables wherever possible. Because your game is in one method, you should be able to avoid using almost any globals.
- When concatenating numbers to strings, use String.valueOf() rather than directly adding them together. This will save many bytes.
External Links
A nice big 4k guide: http://wiki.java.net/bin/view/Games/4KGamesDesign
Please please add replies to this, especially extra tips and guides on how to use the compression tools and pack200. We want this thread to eventually be full of step-by-step guides so that people can focus on their code.