Avoid redundancy of code.
Don't be too defensive in your code. Ie only attempt to handle exceptional conditions when they are expected (catching Exceptions, checking for null references should be really all you need).
When compiling get the compiler to produce class files that don't contain debug code
Don't use the -O switch unless you have to, optimised class files tend to be larger than their unoptimised versions.
To reduce class file size after compilation, use an obfuscator application and set it so that method and variable names are short.
yeah, obfuscation will generally decrease your class size by 30% ish. Though it realy depends if you have alot of
public int thisIsTheCounterThatCountsTheNumberOfTimesICountTheOtherCounter = MyExtremelyLongClassNameThatRealyIsAWasteOfSpace.InitialValueFor_thisIsTheCounterThatCountsTheNumberOfTimesICountTheOtherCounter_Counter;
:)
rob,
they do,
but in each Class's information the names of instance variables, methods and static variables are also stored. (try compiling then decompiling, you will see exactly what names are retreivable from the class file, and which the decompiler has to generate itself)
I think the main reason why they are stored, is to aid debugging. In my opinion the javac compiler should realy have a built in obfuscator cmdline option.
I think intergrating an obfuscator into j2me is being considered for midp2.0, as the class size is a significant part of an apps. footprint size, and when you've got 100ish kb of heap; mem is everything.
Methods calls can often be replaced by the actual code itself which results in a speed up.
For example
public void someMethod() {
int localVar = somePrivateGetter();
....
}
The somePrivateGetter() call can be rewritten like this..
public void someMethod() {
int localVar = this.privateVar;
....
}
The example doesn't result in larger class sizes but if the method is not simple (ie more than a return statement in this case) then the class size does increase.
Another way that optimisation can cause class size increase is loop rollout.
Loop rollout is where a short loop of determinable size can be replaced by a set of lines representing the loop, for example
for(int i=0;i<10;i++) {
System.out.println("i = "+i);
}
can be replaced with...
int i=0;
System.out.println("i = "+(i++));
System.out.println("i = "+(i++));
System.out.println("i = "+(i++));
System.out.println("i = "+(i++));
System.out.println("i = "+(i++));
System.out.println("i = "+(i++));
System.out.println("i = "+(i++));
System.out.println("i = "+(i++));
System.out.println("i = "+(i++));
System.out.println("i = "+(i++));
As you can see, there is an obvious increase in class size involved here