Java Reference
In-Depth Information
Figure 17-4. Network activity from the PeekAndPick application
Optimizing Memory Use
It's easy for J2SE programmers to be blasé about memory usage. After all, having a garbage
collector means that you don't have to worry about explicitly freeing memory—objects that are
no longer in use will be magically harvested by the garbage collector, running in a low-priority
thread. In the J2ME universe, however, memory is scarce and should be treated with respect.
Furthermore, both the allocation of memory and the work of the garbage collector can drag
down the speed of your application. In this section, we'll look at techniques for efficient object
use, particularly with String s and StringBuffer s. Finally, we'll talk about gracefully handling
the situation when there really isn't any memory left.
Creating and Discarding Objects
If you're creating a new object inside a loop, it should be setting off alarm bells in your head.
Every time you create an object (using new ), memory is allocated. Allocating memory takes
time. Worse, objects created at the beginning of a loop are likely to fall out of scope by the end
of the loop, which means that each iteration through the loop pushes the runtime system closer to
running the garbage collector. Here's an example:
// Set up the inputs and results arrays.
Object[] inputs = new Object[1000];
int[] results = new int[1000];
// Process each input to calculate a result.
int length = inputs.length;
for (int i = 0; i < length; i++) {
Processor p = new Processor(inputs[i]);
results[i] = p.calculateResult();
}
Search WWH ::




Custom Search