Developers should realize that only a few optimizations are supported by most Java compilers. That most Java compilers do little when it comes to optimizing code may be surprising, but that is a fact. There are three ways to handle this situation, however.
- Create hand-optimized Java source code in an attempt to achieve better performance.
- Rely on runtime optimizations such as JIT compilers or adaptive compiler technology (HotSpot for example).
- Use third-party optimizing compilers that compile Java source to optimized bytecode.
While going for the first approach, developers should consider the following points:
- Don't optimize for optimization sake; only do so if you have demonstrated that the optimization is necessary. Verify the need for optimization with proven timing techniques or a reliable execution profiler that identifies specific performance issues.
- Optimizations should be applied carefully; otherwise, bugs probably will be introduced. Remember, slow robust code is better than faster unstable code.
- After performing an optimization, profile again to prove that it has had the desired effect. This is especially necessary when implementing optimizations in a system of software in which various integrated modules have or share optimizations.
- There is no universal performance model for JVM technology. Therefore, a technique that produces faster code on one JVM might not do so on another.
One golden rule for producing fast code is to optimize only what is being executed. Time spent optimizing code that does not have a substantial impact on performance is wasted. Typically, 80 to 90 percent of the execution time of an application is spent executing only 10 to 20 percent of its code. The 10 to 20 percent of your code that needs improvement is best found by using performance profilers.
Finally, efficient, fast code is closely related to good design, sound algorithms, and a good understanding of data structures and their implementation.