Java Performance Tips
The First Rule of Optimization: Don’t do it.
The Second Rule of Optimization (for experts only): Don’t do it yet.
Like all performance tips, the following are guidelines and not rules. Code that is well designed and cleanly coded is almost always infinitely preferable to “optimized” code. Invoke these guidelines only when either a positive effect will be seen on the design or that last drop of performance is really necessary.
- Tip #1: Object creation is bad
Excessive object instantiation (especially of short-lived objects) will cause poor performance. This is because object churn causes frequent young generation garbage collections, and young generation garbage-collection algorithms are mostly of the “stop-the-world” type.
- Tip #2: Static is good
If a method can be made static, then make it so. Static methods are not virtual, and so are not dispatched dynamically. Advanced VMs can inline such methods much more easily and readily than instance methods.
- Tip #3: Table switch good, lookup switch bad
Switch statements whose labels are a reasonably compact set are faster than those whose values are more disparate. This is because Java has two bytecodes for switches:
tableswitchandlookupswitch. Table switches are performed using an indirect call, with the switch value providing the offset into a function table. Lookup switches are much slower because they perform a map lookup to find a matching value:function pair.- Tip #4: Small methods are good methods ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access