Performance Comparison in Java

A practical guide to choosing the right Java collection by comparing time complexity, memory, ordering, thread safety, and null-handling across all major implementations.

Choosing the right collection for the job is one of the most common interview scenarios and a crucial day-to-day engineering decision. This lesson consolidates the time complexity, memory characteristics, ordering guarantees, thread-safety status, and null-handling rules for all major Java collections covered in this module, so you can make the right choice confidently.

List Implementations

Implementation add(E) (end) add(i, E) (middle) get(i) remove(i) contains Memory Ordered?
ArrayList O(1) amortized O(n) O(1) O(n) O(n) Low Insertion
LinkedList O(1) O(n) to find, O(1) to link O(n) O(n) to find, O(1) to unlink O(n) High (two pointers per node) Insertion
ArrayDeque O(1) amortized N/A (deque) O(1) at ends O(1) at ends O(n) Low Insertion

Rule of thumb: Use ArrayList by default. Use ArrayDeque as a stack or queue. LinkedList is rarely the right choice — it is slower in practice due to cache misses.

Set Implementations

Implementation add remove contains Ordering Null Thread-safe
HashSet O(1) avg O(1) avg O(1) avg None 1 null No
LinkedHashSet O(1) avg O(1) avg O(1) avg Insertion 1 null No
TreeSet O(log n) O(log n) O(log n) Sorted No No
EnumSet O(1) O(1) O(1) Enum declaration No No

Rule of thumb: HashSet for raw speed. LinkedHashSet when insertion order must be preserved. TreeSet when sorted iteration or range queries are needed. EnumSet for sets of enum values — it is bit-vector backed and extremely fast.

Map Implementations

Implementation put / get / remove Ordering Null key Null value Thread-safe
HashMap O(1) avg, O(log n) worst None 1 null Allowed No
LinkedHashMap O(1) avg Insertion / access 1 null Allowed No
TreeMap O(log n) Sorted (natural or Comparator) No Allowed No
Hashtable O(1) avg None No No Yes (coarse)
ConcurrentHashMap O(1) avg None No No Yes (fine-grained)
EnumMap O(1) Enum declaration No Allowed No

Rule of thumb: HashMap for single-threaded general use. LinkedHashMap for ordered maps or LRU caches. TreeMap for sorted key access. ConcurrentHashMap for concurrent access. Never use Hashtable in new code.

Queue and Deque Implementations

Implementation offer/add poll/remove peek Ordering Thread-safe
ArrayDeque O(1) amortized O(1) O(1) LIFO or FIFO No
PriorityQueue O(log n) O(log n) O(1) Natural / Comparator (min-heap) No
LinkedBlockingQueue O(1) O(1) O(1) FIFO Yes
PriorityBlockingQueue O(log n) O(log n) O(1) Min-heap Yes

HashMap Internal Complexity Detail

Average case (O(1)):     Well-distributed hash codes, low load factor
Worst case (O(n)):       All keys hash to the same bucket, pre-Java 8
Worst case (O(log n)):   Java 8+ — bucket treeified after 8 entries (table ≥ 64)
Resize:                  O(n) — triggered when size > capacity × 0.75

Memory Overhead Comparison

Collection Overhead per element (approximate)
ArrayList ~4 bytes (object reference in array)
LinkedList ~48 bytes (two pointers + object wrapper)
HashMap entry ~48 bytes (key ref, value ref, hash, next pointer, header)
LinkedHashMap entry ~64 bytes (adds before/after pointers)
TreeMap entry ~48 bytes (key ref, value ref, left/right/parent, color bit)
HashSet entry Same as HashMap (element stored as key)

Values are JVM-implementation-specific. Use a profiler for precise measurements.

Decision Guide

Need uniqueness only?
  → No ordering needed:         HashSet
  → Insertion order needed:     LinkedHashSet
  → Sorted order needed:        TreeSet

Need key-value pairs?
  → No ordering, single-thread: HashMap
  → Insertion order:            LinkedHashMap
  → LRU cache:                  LinkedHashMap (access-order + removeEldestEntry)
  → Sorted keys:                TreeMap
  → Concurrent access:          ConcurrentHashMap

Need a queue or stack?
  → General queue/stack:        ArrayDeque
  → Priority-based processing:  PriorityQueue
  → Blocking producer-consumer: LinkedBlockingQueue

Examples

Benchmarking with different Map implementations

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;

public class MapComparison {
    public static void main(String[] args) {
        int n = 100_000;

        // HashMap — fastest for random access
        long start = System.nanoTime();
        Map<Integer, String> hashMap = new HashMap<>();
        for (int i = 0; i < n; i++) hashMap.put(i, "v" + i);
        for (int i = 0; i < n; i++) hashMap.get(i);
        System.out.printf("HashMap:       %,d ns%n", System.nanoTime() - start);

        // TreeMap — O(log n), sorted keys
        start = System.nanoTime();
        Map<Integer, String> treeMap = new TreeMap<>();
        for (int i = 0; i < n; i++) treeMap.put(i, "v" + i);
        for (int i = 0; i < n; i++) treeMap.get(i);
        System.out.printf("TreeMap:       %,d ns%n", System.nanoTime() - start);

        // LinkedHashMap — insertion-order iteration
        start = System.nanoTime();
        Map<Integer, String> linkedMap = new LinkedHashMap<>();
        for (int i = 0; i < n; i++) linkedMap.put(i, "v" + i);
        for (int i = 0; i < n; i++) linkedMap.get(i);
        System.out.printf("LinkedHashMap: %,d ns%n", System.nanoTime() - start);
        // Expected: HashMap ≈ LinkedHashMap < TreeMap
    }
}

Choosing the right Set

import java.util.*;

public class SetComparison {
    public static void main(String[] args) {
        // HashSet — no order
        Set<String> hash = new HashSet<>(List.of("banana", "apple", "cherry"));
        System.out.println(hash);        // order varies, e.g. [banana, cherry, apple]

        // LinkedHashSet — insertion order
        Set<String> linked = new LinkedHashSet<>(List.of("banana", "apple", "cherry"));
        System.out.println(linked);      // [banana, apple, cherry]

        // TreeSet — sorted order
        Set<String> tree = new TreeSet<>(List.of("banana", "apple", "cherry"));
        System.out.println(tree);        // [apple, banana, cherry]
    }
}

Common Mistakes

  1. Using LinkedList as a general-purpose list. Despite O(1) insertion at known positions, LinkedList is almost always slower than ArrayList in practice because of cache misses (nodes are scattered in memory). ArrayList's contiguous array is much more cache-friendly.

  2. Assuming HashMap.get is always O(1). In pathological cases (all keys with the same hash code) before Java 8, HashMap degrades to O(n). Post-Java 8 treeification caps the worst case at O(log n), but deliberate hash flooding is still possible. In security-sensitive contexts, use String.hashCode carefully.

  3. Choosing TreeMap when only a sorted snapshot is needed. Maintaining a TreeMap for the entire lifetime of the data just to get a sorted view at the end is wasteful — it pays O(log n) per every put. Collect into a HashMap and use Collections.sort or stream().sorted() at the end for a one-time sort.

  4. Using Hashtable or synchronizedMap for high-concurrency scenarios. Both serialize all access through a single lock. Under contention this becomes a throughput bottleneck. Use ConcurrentHashMap, which allows concurrent reads and parallel writes to different buckets.

  5. Ignoring initial capacity. Repeated resizing of a HashMap or ArrayList doubles the structure on each trigger, causing multiple O(n) rehash or copy operations. Pre-size when the expected size is known: new HashMap<>(expectedEntries * 4 / 3 + 1).

Best Practices

  • Always declare variables with the narrowest useful interface type (List, Set, Map, Queue) rather than a concrete class.
  • Profile before optimising — hash collections are faster in practice than tree-based ones for most workloads, but memory pressure or GC pauses can invert the comparison.
  • Prefer immutable collections (List.of, Set.of, Map.of) when the data does not change — they are safe to share across threads and cannot be accidentally modified.
  • Match the null-handling of your chosen collection to your data: ConcurrentHashMap and TreeMap forbid null keys; always check before migrating code.
  • Consider EnumSet and EnumMap for enum-keyed data — they are significantly faster and more memory-efficient than their hash-based counterparts.

Interview Questions

1. When would you choose ArrayList over LinkedList?

Almost always. ArrayList has O(1) random access, better cache locality (contiguous memory), and lower per-element overhead. LinkedList has O(1) insertion at a known node position, but finding that position is O(n), making it rarely faster. ArrayDeque is a better choice for queue or stack use cases.

2. What is the time complexity of HashMap get and put in the worst case?

Before Java 8: O(n) if all keys hash to the same bucket (degenerate linked list). Java 8+: O(log n) because buckets with more than 8 entries (table size ≥ 64) are treeified into red-black trees. Average case remains O(1) with a well-distributed hash function.

3. How do you choose between HashMap and TreeMap?

Use HashMap (O(1) average) when you need fast key-value lookup without any ordering requirement. Use TreeMap (O(log n)) when you need keys in sorted order, range queries (subMap, headMap, tailMap), or navigation methods (floorKey, ceilingKey).

4. What is the space cost of LinkedHashMap compared to HashMap?

Each LinkedHashMap entry carries two additional object references (before and after) for the doubly-linked list, adding approximately 16 bytes per entry on a 64-bit JVM compared to HashMap. The extra cost is constant per entry, not proportional to the size.

5. Why is ConcurrentHashMap preferred over Collections.synchronizedMap for concurrent use?

Collections.synchronizedMap uses a single mutex for all operations, allowing only one thread to proceed at a time — identical to Hashtable. ConcurrentHashMap uses CAS for writes to empty bins and per-bin locking for non-empty bins, allowing multiple threads to write to different bins simultaneously. It also provides atomic compound operations (computeIfAbsent, merge) that synchronizedMap does not.

6. When should you use TreeSet instead of sorting a HashSet?

Use TreeSet when you need elements to remain sorted continuously (e.g., you add and remove elements frequently and always need the minimum or maximum). If you only need a sorted snapshot at a fixed point in time, collect into a HashSet for O(1) insertions and sort once with Collections.sort (O(n log n)).

7. What are the key differences in null handling across Map implementations?

HashMap: one null key, many null values. LinkedHashMap: same as HashMap. TreeMap: no null keys with natural ordering (NullPointerException), null values allowed. Hashtable: no null keys, no null values (NPE on insert). ConcurrentHashMap: no null keys, no null values (NPE on insert). Always verify null contracts when migrating between implementations.

Summary

  • ArrayList and HashMap are the right defaults for single-threaded use; they offer the best practical performance.
  • Use TreeSet / TreeMap only when sorted order or range queries are required — the O(log n) cost is constant but real.
  • ConcurrentHashMap is the only recommended concurrent map; avoid Hashtable and synchronizedMap under contention.
  • Pre-size hash structures to avoid costly resizes; use EnumSet/EnumMap for enum-keyed data.
  • Choose the right collection once and profile before switching — the difference is often smaller than expected.

Continue Learning

Previous: Collections Utility

Was this guide helpful?

CodeWithVenu is free to read, with no paywall. If this guide saved you time or helped you prepare, a small voluntary contribution helps me write more practical tutorials, architecture guides, and interview-prep content.