Performance testing Java HashMap vs TreeMap with large key sets
A Map choice can look harmless when a unit test holds a dozen entries, then become a source of latency, allocation pressure, and CPU cost once hundreds of thousands or millions of keys are stored. HashMap and TreeMap both implement Map, yet they differ in lookup behaviour, ordering, iteration, and memory use. Large key sets expose those differences because cache misses, comparisons, garbage collection, and resizing shape the result.
Performance testing should reproduce those pressures rather than declare a winner from Big O notation. Australian teams also need to fit the result to local conditions: Sydney and Melbourne anchor major cloud regions, Brisbane and Perth users can have different network paths, and infrastructure owners are naturally keen on the “bang for buck” of lower memory use and smaller AUD cloud bills. The useful outcome is evidence for a defined workload, JVM, and host.
Why the map choice changes under load
HashMap stores entries in hash buckets and normally provides constant-time get, put, and remove operations. Its average cost comes from hashing and locating a bucket, while equality checks confirm the key. TreeMap maintains a red-black tree ordered by natural key order or a supplied Comparator, giving logarithmic lookup and predictable tree depth. That extra structure buys navigation features, but it also adds comparisons and pointer traversal.
Scale magnifies the implementation details. A HashMap can resize as entries cross its load-factor threshold, reallocating its bucket array and moving entries. Buckets with persistent collisions may also become tree-based internally in modern Java, adding work to an otherwise hash-oriented structure. A TreeMap avoids array resizing but balances rotations and maintains parent, left, and right links for every entry.
The access pattern matters more than the map name. A lookup cache keyed by customer ID has different requirements from a registry that must return the smallest matching value. Benchmarking both with the same method is fair only when it asks the same question. For a Sydney payments team or a Melbourne SaaS platform, that question might be dominated by random reads, while an overnight batch may favour ordered scans.
Behavioural trade-offs before the benchmark
The practical differences are clear from their data structures:
| Concern | HashMap |
TreeMap |
|---|---|---|
| Typical key lookup | Average O(1) | O(log n) |
| Ordering | Unsorted | Sorted, naturally or by comparator |
| Iteration | Bucket order | Key order |
| Bulk insertion | Usually cheaper; may resize | Comparisons and balancing add cost |
| Memory profile | Bucket array plus entry objects | Entry objects with several tree links |
| Navigation | Basic map operations | floorKey, ceilingKey, and range views |
| Null handling | Allows one null key and null values | Natural ordering rejects a null key |
| Concurrency | Not thread-safe | Not thread-safe |
These are behavioural expectations, not measured results. HashMap often wins for random hits, misses, and updates when ordering has no value. TreeMap becomes attractive when ordered iteration or range queries are frequent, especially with an inexpensive comparator. A service that scans the whole map for every request may also gain more from TreeMap than one that performs isolated point lookups.
Key representation can reverse the apparent result. Integer hashing is inexpensive, String caches its hash after calculation, and a custom record or domain object may hash many fields. Equality and comparator work then varies too. Keep the key class, hash distribution, comparator, and hit ratio aligned with production; otherwise the benchmark can favour a map for the wrong reason.
Building a representative JMH benchmark
Use JMH rather than a hand-written stopwatch. Its warm-up, forked JVMs, dead-code protections, and Mode.SampleTime percentiles make repeated measurements much more credible. Give each operation its own benchmark method, and use Blackhole or a returned value so the optimiser cannot discard the lookup. Test at least two key counts, such as 100,000 and 1,000,000, then add a larger set only if the production heap can hold it with realistic headroom.
Separate the scenarios. Measure random hit lookup, random miss lookup, insertion into a fresh map, replacement of an existing value, ordered or unordered iteration, and removal. Build the maps in a trial-level setup when measuring reads, but include map construction in a separate benchmark when insertion is the subject. Pre-sizing HashMap is reasonable for a tuned service, although a second run without pre-sizing reveals resize costs that TreeMap never pays.
Control the environment with the same JDK build, JVM flags, heap size, garbage collector, CPU, and operating system. Use a fixed random seed and report it. Run several forks, retain confidence intervals, and inspect p50, p95, and p99 latency instead of relying on mean time. A Sydney ap-southeast-2 host and a laptop in Brisbane do not represent the same machine, so publish the instance type and processor details with the results.
Reading latency, throughput, and tail results
Throughput answers how many operations completed per second, while latency shows how long callers waited. Both matter in cloud services billed by capacity and under response-time objectives. Read them together, then check whether a fast average hides occasional pauses caused by garbage collection or bucket resizing.
Signals that favour HashMap:
- Higher random-lookup and mixed-update throughput when order is irrelevant.
- Often lower retained memory and less structural overhead for common key types.
- Strong results for point lookups against data already used by the service.
- Weakness under skewed hashes, deliberate collisions, or frequent resizing.
Signals that favour TreeMap:
- Logarithmic scaling with less sensitivity to hash quality.
- Better results when cheap ordered iteration replaces repeated full scans.
- Predictable behaviour as the key set grows beyond the most active cache.
- Higher CPU and memory cost when ordering adds little business value.
Treat differences smaller than the confidence interval as inconclusive. Also calculate the cost of useful work: a slower TreeMap lookup can still be the better choice if it avoids scanning hundreds of thousands of entries elsewhere. In an Australian deployment, test the same JVM within the chosen region, then validate end-to-end latency from the main client locations rather than assuming network and application costs disappear.
A slower map is not automatically worse. A HashMap can excel at point reads, while TreeMap can win on ordered workloads or queries that would otherwise scan a large collection. Compare the application-level objective as well as raw operations per second. Keep the benchmark results linked to the exact commit so later changes can be compared fairly.
Memory pressure and Australian deployment realities
HashMap needs a bucket array plus an entry object for each mapping. TreeMap needs an entry for each mapping as well, but each entry also carries tree links and balancing metadata. Shared key and value objects are identical in both designs, so the live-key payload can obscure the structural difference. Measure retained heap after a full garbage collection, not just allocation totals, and watch promotion into the old generation.
Heap pressure can change a close latency result. A map that triggers extra collections may show higher p99 values or consume more container CPU, even when its average operation is quick. Record GC pause time and allocation rate with GC logs or JFR. Do not compensate by adding unlimited memory: a larger heap may remove pauses while increasing cost, which is a poor trade for many Australian workloads focused on “bang for buck”.
Local hosting adds another constraint. Many services run in AWS Sydney or Azure Australia East in Melbourne, with contractual data-residency rules and Australian privacy requirements influencing placement. If the benchmark runs in another jurisdiction, CPU behaviour may still be useful, but it is not a complete substitute for testing in-region. Use synthetic keys for realistic scale tests; Australian customer records should not be copied into a performance environment simply to make the dataset look authentic.
Selecting and validating the production map
Choose HashMap when lookups dominate and ordering is unnecessary. Choose TreeMap when sorted iteration, bounded ranges, nearest-key navigation, or stable ordered output are core requirements. Review the workload with the engineers who own the service, since business semantics often reveal a better data structure than raw lookup speed alone. A sorted copy of keys, for example, may support a narrow range query without imposing tree overhead on every normal update.
Neither class is safe for concurrent mutation. A shared service cache may need ConcurrentHashMap; a concurrent ordered structure may suit ConcurrentSkipListMap, subject to its own benchmark. Test contention, lock behaviour, and consistency separately from the single-threaded large-key-set comparison. Also test poor hash distributions and comparator changes, because adversarial or accidental collisions can invalidate tidy expectations.
Keep the results as a repeatable build artefact rather than a wiki anecdote. Include source code, JMH parameters, raw results, JVM settings, and an explicit workload description so another engineer can reproduce them. The concrete next step is to add a JMH benchmark with one million production-shaped keys, run it on the same JVM and host used by the service, and archive its latency, allocation, and garbage-collection results beside the build.