
Java Programming Guidelines
String str = "testing"; str = str + "abc";
The compiler translates this code as:
String str = "testing";
StringBuffer tmp = new StringBuffer(str); tmp.append("abc");
str = tmp.toString();
Therefore, copying is inherently expensive and overusing it can reduce performance significantly.
Assign null to Variables That Are No Longer Needed
Explicitly assigning a null value to variables that are no longer needed helps the garbage collector to identify the parts of memory that can be safely reclaimed. Although Java provides memory management, it does not prevent memory leaks or using excessive amounts of memory.
An application may induce memory leaks by not releasing object references. Doing so prevents the Java garbage collector from reclaiming those objects, and results in increasing amounts of memory being used. Explicitly nullifying references to variables after their use allows the garbage collector to reclaim memory.
One way to detect memory leaks is to employ profiling tools and take memory snapshots after each transaction. A
Declare Methods as final Only If Necessary
Modern optimizing dynamic compilers can perform inlining and other
Only if you are absolutely certain that a method must not be overridden, use the final keyword.
Declare Constants as static final
The dynamic compiler can perform some constant folding optimizations easily, when you declare constants as static final variables.
Avoid Finalizers
Adding finalizers to code makes the garbage collector more expensive and unpredictable. The virtual machine does not guarantee the time at which finalizers are run. Finalizers may not always be executed, before the program exits. Releasing critical resources in finalize() methods may lead to unpredictable application behavior.
28 | Sun GlassFish Enterprise Server 2.1 Performance Tuning Guide • January 2009 |