Java size optimization


I'm probably not the right person to write this article since I've been coding in Java less than one year, but I've decided to share some of my knowledge about optimizing Java programs for size.

1. Global variables

This is one of the most interesting part of Java programs. You should try to keep the names of your global variables and functions as short as possible because the entire name of each variable and function will be saved as it is to the bytecode (.class). There are several programs (like Jshrink) which will do the job for you, but for 4k intros it's probably best doing it yourself for the best result.

You should also try to use integer as much as possible instead of using float or long.

2. Loops

Start your loops from the top if possible. Instead of

for(int i=0; i<200; i++)
    k += f;


for(int i=199; i>=0; i--)
    k += f;

This is 1(!) byte smaller.

3. Compiler

Use -g:none option when compiling in javac. This way the compiler doesn't generate any debugging info and your programs gets a lot smaller. For example, my 4k intro, Vuctors, got 694 bytes smaller by doing this! You may also try to let the compiler do some optimization using -O option.

4. Compression

I bet there's no way doing a decent Java 4k intro without using any compression. For Java programs there are two possibilities: JAR or ZIP. JAR doesn't seem to get as good compression ratios as ZIP.

To use compressed bytecode is simple. Just pack the bytecode like any other ZIP/JAR archive. After that you need to change your HTML code a bit. Normally you would probably use a code like this to get your Java applet going

<APPLET WIDTH=512 HEIGHT=256 CODE="intro.class"></APPLET>

but if you had a compressed ZIP archive, you would use a HTML code like this

<APPLET WIDTH=512 HEIGHT=256 CODE="intro.class" ARCHIVE=""> </APPLET>

Now the browser would open first and search it for intro.class. You don't need to code any fancy uncompressor, you just need a new enough browser.

In Windows it's also possible to use CAB files, which compress even better than ZIP, but I really can't say it then would be a Java program anymore.

Hmm, this article was quite short, but I hope somebody will find it useful. And now when Assembly organizers don't accept DOS 4k intros anymore, I think Java could be a good new alternative.