Java Reference
In-Depth Information
The second column makes it clear that there is a small penalty when using any data protec-
tion technique as opposed to simple unsynchronized access. However, keep in mind this is a
microbenchmark executing 500 million operations—so the difference in time per operation is
on the order of 15 nanoseconds. If the operation in question is executed frequently enough in
the target application, the performance penalty will be somewhat noticeable. In most cases,
the difference will be outweighed by far larger inefficiencies in other areas of the application.
Remember also that the absolute number here is completely determined by the target ma-
chine the test was run on (my home machine with a four-core AMD Athlon); to get a more
realistic measurement, the test would need to be run on hardware that is the same as the tar-
get environment.
So, given a choice between a synchronized Vector and an unsynchronized ArrayList ,
which should be used? Access to the ArrayList will be slightly faster, and depending on
how often the list is accessed, there can be a measurable performance difference here. (As
noted in Chapter 9 , excessive calls to the synchronized method can be quite painful for per-
formance on certain hardware platforms as well.)
On the other hand, this assumes that the code will never be accessed by more than one
thread. That may be true today, but what about tomorrow? If that might change, then it is bet-
ter to use the synchronized collection now and mitigate any performance impact that results.
This is a design choice, and whether future-proofing code to be thread-safe is worth the time
and effort will depend on the circumstances of the application being developed.
If the choice is between using an unsynchronized collection and a collection using CAS prin-
ciples (e.g., a HashMap compared to a ConcurrentHashMap ), then the performance difference
is even less important. CAS-based classes show virtually no overhead when used in an un-
contended environment (but keep reading for a discussion of memory differences in the par-
ticular case of hashmaps).
Collection Sizing
Collection classes are designed to hold an arbitrary number of data elements and to expand
as necessary, as new items are added to the collection. There are two performance considera-
tions here.
Although the data types provided by collection classes in Java are quite rich, at a basic level
those classes must hold their data using only Java primitive data types: numbers ( integer s,
double s, and so on), object references, and arrays of those types. Hence, an ArrayList con-
tains an actual array:
Search WWH ::

Custom Search