I've recently been writing a lot of code in C and am now switching over to Java. I'm currently implementing a large data structure and was wondering whether there were any optimization flags I can turn on when I invoke the Java compiler in order to improve performance like in gcc.
I'm used to:
gcc -O3 -NDEBUG MyProgram.c
is there an analogous command for javac
?
I'm using JDK and am running Ubuntu 10.04.
Optimization in Java is mostly done by the JIT compiler at runtime. Hence there is no point trying to instruct it to optimize a certain way at compile time (when it is creating only bytecode anyway). The JIT will almost surely make better decisions on the spot, knowing the exact environment and observing the actual patterns of execution of specific parts of your code.
There are some specific compiler options affecting performance, but these are for tuning the JVM (including the garbage collector) rather than optimizing the code itself.
There's no equivalent to -O3
or any of the -O
levels, but there are specific tuning options you have access to via -XX:
. There's a full list available here.
This assumes you are using the Oracle-provided JVM, however, and it may differ based on your environment ("using JDK" doesn't really describe which version you are using)
You can optimize Java byte code by running it through Proguard, a popular Java obfuscator. It will shrink, optimize, and obfuscate code in that order with switches to control pretty much everything. It will remove unused methods and variables, inline code, remove dead branches, merge identical code and perform dozens of other optimizations. The result is a jar file which does the same as your input but takes up less space and runs faster.
It's a must-have for commercial client-side software.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With