开发者

javac optimization flags [duplicate]

This question already has answers here: Optimization by Java Compiler 开发者_JAVA百科 (6 answers) Closed 8 years ago.

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.


Java code optimisations are applied during runtime as the Hotspot VM sees fit. (As far as I know, this involves keeping track of method invocation counts and compiling frequently called methods into native code and trying several types of optimisations as well.)

The only remotely connected switch you can use with javac is -g:none which tells the compiler to omit debug information: this doesn't really affect the performance of your code but it decreases the size of the .class files.

When you start the VM though, you have a choice between -server and -client options, which will affect the range of optimisations and how early they kick in.


The JVM and JIT will do most of optimizations for your code, at runtime, so you will have to bite the bullet and trust the underlying bytecode manipulators (JVM and JIT) to do the optimizations.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜