Java Reference
In-Depth Information
to set the variable to null explicitly. For example, if a buffer is allocated at the beginning of a
method, but then no longer needed in the method, the garbage collector cannot reclaim the buffer
because the variable still points to the buffer. If the variable is explicitly set to null , the buffer is
no longer referenced and can be reclaimed by the garbage collection.
For J2ME, it is also very important to always dispose resources such as record stores or
connections when they are no longer needed. J2ME does not support finalization, which means
that system resources cannot be closed automatically during garbage collection. Thus, if the
reference to a system resource is removed without closing the resource, the resource will stay
allocated until system cleanup, when the program is terminated completely.
Loop Condition Checking
When you're trying to optimize execution speed, loops are the most important pieces of code to look at:
statements inside a loop are executed several times. Thus, even small optimizations can have a
significant effect.
A standard method to speed up loops is to move constant expressions out of the loop. For example, the
following simple for loop iterates all elements of the Vector vector :
for (int i = 0; i < vector.size(); i++) ...
In this line, the size() method of vector is called at each iteration. This repetition can be avoided
by storing the size in a local variable:
int size = vector.size();
for (i for (int i = 0; i < size; i++) ...
Please note that access to local variables is generally less expensive than access to instance or class
variables. Here, the size() method is called only once and stored in a local variable for fast access
inside the loop. If the direction the vector is iterated is not important, counting down may be a
reasonable alternative to introducing a new variable:
for (int i = vector.size()-1; i >= 0; i--) ...
The same technique can be applied to all expressions that are calculated inside the loop, but do not
change with the iterations.
Avoiding Recursion
Another common optimization technique that may speed up program execution and that definitely
saves memory is to transform recursions into iterations. You can usually do so if there is only one
simple recursion call. For example, the factorial of a number n is defined as n multiplied by the
factorial of ( n -1). The corresponding recursive function is
public static void fact (int n) {
return n == 1 ? 1 : n * fact (n - 1);
}
 
 
Search WWH ::




Custom Search