Java Reference
In-Depth Information
Whenever coding for performance, it is a good idea to first write the code in
a natural way and then profile it with the built-in profiling tools to see where the
problem areas are. Finally, tune those problem areas. In general, extra care in
coding should be taken in loops with lots of iterations and in methods that are
called frequently.
For the problem areas, here is a list of some basic performance tips:
Local variables run faster than instance and static variables.
The
long
and
double
type variables typically require extra time to access and modify
since they contain additional bytes compared to
int
and
float
.However, significantly
slower performance is not true of all JVMs on all platforms since some take advantage
of particular processor capabilities.
The JVM bytecode is weighted towards
int
operations so use
int
type except where
you specifically need to use one of the other types. Math operations with the shorter
integer types are widened in the JVM to
int
.For example, a sum of two
byte
values
results in an
int
value (that may be cast back to a
byte
if the result is to be stored into
a
byte
variable).
Use the
x+= A
type of commands rather than
x = x+A
. The first requires one
instruction and the latter four.
If you are concatenating lots of strings, use
StringBuffer
and its
append()
method
instead of the
String “+
„
operator. In Java 5.0 and above, use
StringBuilder
instead.
As demonstrated in the
TimeTest
example above, the original Java utility classes like
Vector
,
Enumeration
, and
Hashtable
are slow because they use synchronization
for thread safety. Although synchronization overhead has been significantly reduced
in modern versions of Java, if you do not require synchronization, then the newer
utilities from the Java Collections Framework are normally superior. The new classes
ArrayList
and
HashMap
generally replace
Vector
and
Hashtable
, respectively,
and
Iterator
is preferred over
Enumeration
.
Av oid creating lots of objects if possible, especially in loops. Creating an object takes up
considerable time and uses up memory resources and requires the Java garbage collector
to do more work to reclaim abandoned memory.
Av oid method calls in a loop as much as possible. That is, do your loops inside of
methods rather than calling methods inside of loops.
Performance can vary significantly among different JVMs for the same platform. Do
timing measurements for all the JVMs that would potentially be used with your program.
See the topic by Shirazi [6] for a complete discourse on performance enhance-
ments.
12.9 Lifelong Java learning
Part I introduced the basics of Java programming and you can now create applets
and applications with graphical user interfaces, threads, I/O, image processing,
Search WWH ::
Custom Search