Java Reference
In-Depth Information
If you are using the persistent storage APIs, you may be tempted to wrap stream classes around
the record data. For example, you might read a record, then wrap a ByteArrayInputStream
around the record's data, and then wrap a DataInputStream around the ByteArrayInputStream
to read primitive types from the record. This is likely too heavy to be practical. If at all possible,
work directly with the record's byte array.
Use Buffered I/O
Don't read bytes one at a time from a stream, and don't write them out one at a time. Although
the stream classes provide methods that read and write a single byte, you should avoid them if
at all possible. It will almost always be more efficient to read or write a whole array full of data.
File and network access is usually quite slow.
J2SE includes BufferedReader and BufferedWriter classes that provide buffering function-
ality “for free.” There is no such luxury in the MIDP universe, so if you want to use buffering,
you'll have to do it yourself.
Be Clean
One simple piece of advice is to clean up after yourself. Releasing resources as soon as you are
done with them can improve the performance of your application. If you have internal arrays
or data structures, you should free them when you're not using them. One way to do this is to
set your array reference to null so that the array can be garbage collected. You could even call
the garbage collector explicitly with System.gc() if you're anxious to release memory back to
the runtime system.
Caution On most MIDP devices, continually acquiring and releasing resources can also degrade perfor-
mance. This trade-off must be evaluated carefully.
Network connections should also be released as soon as you're done with them. One good
way to do this is to use a finally clause. Consider the following code, which does not use a
finally clause:
HttpConnection hc = null;
InputStream in = null;
try {
hc = (HttpConnection)Connector.open(url);
in = hc.openInputStream();
// Read data from in.
in.close();
hc.close();
}
catch (IOException ioe) {
// Handle the exception.
}
 
Search WWH ::




Custom Search