Search code examples
javaoptimizationjvm

How to write efficient Java code?


As all of you may know, Java code is compiled and interpreted by JVMs. My questions deal with optimization: Is it optimized at run-time by the JVM only or also at compile-time?

In order to write efficient code, where can I find the list of supported optimizations? Or are JVM optimizations powerful enough so that I just have to write code that is readable and easy to maintain regardless of speed performance?


Solution

  • Most optimisation is done by the JVM. There's generally more scope for optimisation at the JIT level than at compile-time. (The "optimise" flag was actually taken out of javac, because it turned out that some "optimisations" actually hurt performance in the real world.)

    In general (and this applies to many languages/platforms, not just Java):

    • Write code that is as readable and maintainable as possible.
    • Have performance goals and benchmarks so you can always measure performance
    • Put effort into making your architecture perform; it's hard to change that later (compared with changing implementation)
    • Think about performance more in terms of complexity of algorithms than "make it 10% faster": a change from O(n^2) to O(n) is (generally) much more important. (It very much depends on what the real world usage will be though - if you're only going to be dealing with small values of n, the "theoretically better" algorithm can easily end up being slower due to constant factors.)
    • Use a profiler to determine where your bottlenecks are
    • Only micro-optimise at the cost of readability when the profiler suggests it's worth doing
    • Measure after such an optimisation - you may not have actually had much impact, in which case roll back