5.5 Increasing the Application's Performance
5.5.1 Good Programming Practices
Following is a list of good programming practices to increase performance. These practices are
not just specifically for web application development. However, due to the resource intensive
nature of servlets, good code becomes even more important. (A servlet is instantiated once, and
then executed many times, depending on the load of the web site. Inefficiencies can be
magnified over time).
Avoid string concatenation. Java concatenates two strings internally by instantiating a
StringBuffer object, and using the StringBuffer's append() method to append the second
string to the first string. When concatenating several strings with the + operator, several
instances of string buffer objects are created, used, and then garbage collected, thus,
system resources are wasted. String concatenation can be avoided by using the
StringBuffer object as shown in the code example.
// StringBuffer example
String user = "John";
// The pre defined size of the StringBuffer is 16 characters.
// To avoid the need for resizing, set the initial size to 50 chars.
StringBuffer strBuffer = new StringBuffer(50);
strBuffer.append("The user ");
strBuffer.append(" is currently logged in.");
Avoid unnecessary object instantiations. Each object that is instantiated requires system
resources (memory) during its life cycle. Try to avoid the creation of new objects if
Free resources when they are no longer needed. When an object is no longer needed, it
can be marked to be garbage collected. In Java, simply set the object to null, and the
garbage collector can free the associated resources. (This is not required for local
variables, since they automatically go out of scope when a function is terminated.)
Use final classes and methods. The compiler will optimize a class declared final. This is
because the compiler knows no subclasses can ever be created in the hierarchy.
Similarly, a final method can be inlined by the compiler to avoid the overhead of an extra