Java Reference
In-Depth Information
long elapsed = t2-t1;
vec.clear ();
vec = null;
System.gc ();
return elapsed;
} // testv
In this method we first populate a Vector with Integer objects. Then we begin
to fetch from the Vector and accumulate the sum. In order to allow the Hotspot
compiler time to warm up, we first perform a short summation loop without
timing. The number of warm-up loops is specified by one of the command line
parameters. After warming up we sleep a short while. The purpose of the sleep is
to relinquish the processor so that the Hotspot compiler can finish a background
compile of the loop if needed.
Finally we begin the timing loop by calling System.currentTime-
Millis() , followed by the loop itself (actually an inner and outer loop) and
then another call to System.currentTimeMillis() so we can calculate
the elapsed time. We then clear the Vector , set the reference to null , and
request garbage collection ( System.gc () ). The elapsed time is returned to
doTests() where it is printed to the console.
The command-line parameters adjust the number of warm-up loops, the sleep
time, the number of inner and outer loops to be timed, and the total number of
times to run the tests. If you download this code you can experiment with the
various parameters to see what effect they have on the timing results. The results
can vary widely based on the platform in use.
On one system we find that Vector is consistently the slowest, as expected.
The ArrayList is slightly faster (typically 80% of the Vector time or less)
and the fastest of all, as expected, is the plain object array, which is nearly
twice as fast as Vector .Ofspecial interest is the Java 5.0 parameterized type
ArrayList < Integer > ,which is consistently slightly faster than the unparam-
eterized ArrayList , perhaps due to removing the need for casting from Object
type to Integer type. On a different platform, we observed about the same rel-
ative performance between ArrayList and Vector but a factor of nearly nine
between a plain array and a Vector .Onyet another platform, we've seen a factor
of about three between an array and a Vector .Onone other platform the array
is only about 20% faster than the ArrayList with both about twice as fast as
the Vector . The moral of this story is that the container type chosen can lead
to an important performance difference. Arrays are almost certainly always the
fastest and the synchronized collection objects are the slowest with the newer
unsynchronized collection objects somewhere in between. Just where in between
is platform dependent. Perhaps a second moral is to be sure to test your code on
the platform or platforms on which it will be deployed.
 
Search WWH ::




Custom Search