Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javac optimization flags [duplicate]

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.

like image 482
themaestro Avatar asked Feb 14 '11 21:02

themaestro


3 Answers

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.

like image 140
Péter Török Avatar answered Nov 09 '22 13:11

Péter Török


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)

like image 23
Daniel DiPaolo Avatar answered Nov 09 '22 11:11

Daniel DiPaolo


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.

like image 16
locka Avatar answered Nov 09 '22 13:11

locka