Java 2 Collections

The collections framework introduced with Java 2 comes with a set of collection classes in the JDK. Each class has its own performance strengths and weaknesses, which I cover here. The collection implementations use the synchronized-wrapper framework to provide synchronized classes; otherwise, the implementations are unsynchronized (except for two exceptions noted shortly). Collection classes wrapped in synchronized wrappers are always slower than unwrapped, unsynchronized classes. Nevertheless, my recommendation is generally to use objects within synchronized wrappers. You can selectively “unwrap” objects when they have been identified as part of a bottleneck and when the synchronization is not necessary. (The performance aspects of thread-safe collections are discussed in detail in Chapter 10. Synchronized wrappers are also discussed in that chapter, in Section 10.4.1.)

Table 11-1 summarizes the performance attributes of the collection classes.

Table 11-1. Performance Attributes of Java 2 Collection Classes

Interface

Class

Synchronized?

 

Set

HashSet

No

Fastest Set; slower than HashMap but implements the Set interface (HashMap does not)

 

TreeSet

No

Slower than HashSet; provides iteration of keys in order

Map

HashMap

No

Fastest Map

 

Hashtable

Yes

Slower than HashMap, but faster than synchronized HashMap

 

TreeMap

No

Slower than Hashtable and HashMap; provides iteration of keys in order

List

ArrayList

No

Fastest List

Get Java Performance Tuning now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.