Java Reference
In-Depth Information
Tip One possible strategy in production programming is an attempt to allocate all memory up front, when
the application first starts.
Coding for Speed
Small devices have small, relatively slow processors. Part of your task as a developer is ensuring
your application runs fast enough that users won't reject it.
Optimize Loops
One simple optimization has to do with looping. A typical loop through a Vector v might look
like this:
for (int i = 0; i < v.size(); i++) {
Object o = v.elementAt(i);
// Process the Object o.
}
Each time through the loop, v 's size() method is called. An optimized version would store
the size of the vector first, like this:
int size = v.size();
for (int i = 0; i < size; i++) {
Object o = v.elementAt(i);
// Process the Object o.
}
This is a simple example, but it illustrates that loop conditions are one place you can look
for speed optimizations.
Use Arrays Instead of Objects
Arrays are usually faster and leaner than collection classes. We touched on this theme earlier in
our discussion of String s and StringBuffer s; if it's not too clumsy, using character arrays
directly will probably be more efficient than dealing with String and StringBuffer objects. The
same rule applies to the MIDP collection classes Vector and Hashtable . Although Vector and
Hashtable are simple and convenient, they do impose some overhead that can be trimmed.
Vector is basically just a wrapper for an array, so if you can work with an array directly, you'll
save yourself some memory and processing time. Similarly, if you have a simple mapping of
key objects to value objects, it might make sense to use object arrays instead of Hashtable .
If you do decide to use Hashtable or Vector , try to size them correctly when you create
them. Both Vector and Hashtable grow larger as needed, but it is relatively expensive. Vector
creates a new internal array and copies elements from the old array to the new array. Hashtable
allocates new arrays and performs a computationally expensive operation called rehashing .
Both Vector and Hashtable have constructors that allow you to specify the initial size of the
collection. You should specify the initial size of these collections as accurately as possible.
 
Search WWH ::




Custom Search