Quick revision
The short answer
All three structures can serve 50,000 lookups per second easily, so the real differences are memory and refresh. A HashMap gives O(1) average lookups but costs roughly 70 bytes per entry once boxed keys and values are counted, a TreeMap is O(log n) with pointer chasing and similar or higher memory, and sorted parallel primitive arrays with binary search need about 21 comparisons per lookup and a fraction of the memory. For hourly refresh, we build the new structure off to the side and swap one volatile reference.
What to remember
In this answer, we saw that 50,000 lookups per second is a light load for any of the three structures, so memory and refresh decide the choice. A HashMap or TreeMap of boxed values costs around 70 bytes per entry and millions of objects for the garbage collector, while two sorted primitive arrays cost 16 bytes per entry and answer each lookup in about 21 cache-friendly comparisons. TreeMap is only worth it for ordered or range queries. We refresh by building a new immutable table and swapping a volatile reference, and we confirm the choice with JMH and a heap histogram.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
All three structures can serve 50,000 lookups per second easily, so the real differences are memory and refresh. A HashMap gives O(1) average lookups but costs roughly 70 bytes per entry once boxed keys and values are counted, a TreeMap is O(log n) with pointer chasing and similar or higher memory, and sorted parallel primitive arrays with binary search need about 21 comparisons per lookup and a fraction of the memory. For hourly refresh, we build the new structure off to the side and swap one volatile reference.
Why this question is asked
Lookup tables loaded at startup are everywhere: prices, tax rates, currency codes, feature flags. Interviewers like this question because a quick answer ("HashMap, it is O(1)") misses what actually hurts in production at this size, which is heap use, garbage collection and what readers see during a refresh. In this answer, we will first check whether 50,000 lookups per second is even a hard load, then work out the memory of each option for 2 million entries, look at how each one behaves on lookup, build a sorted-array version in code, design the hourly refresh, and finish with how we would confirm the choice with measurements.
1Is 50,000 Lookups per Second a Hard Load?
Before choosing a structure, it helps to put the numbers side by side. A HashMap lookup on a warm map takes somewhere around 20 to 50 nanoseconds. A binary search over 2 million entries takes about 21 comparisons, because log2(2,000,000) is about 20.9, and even if several of those comparisons miss the CPU cache, the lookup stays well under a microsecond.
At 50,000 lookups per second and a pessimistic 500 nanoseconds each, the service spends 25 milliseconds of CPU per second on lookups, which is 2.5 percent of one core. So all three options are fast enough. That changes the question: we are not choosing the fastest structure, we are choosing the one that is fast enough while using the least memory and refreshing safely. With 2 million entries, memory is where the options really differ.
2Counting the Memory of Each Option
Let us assume the SKU is a long and the price is stored as a long number of cents. Java collections cannot hold primitives, so a HashMap<Long, Long> holds a boxed Long object for every key and every value. With compressed pointers, a Long object takes 16 bytes. A HashMap entry is a Node object holding the hash, the key, the value and a next pointer, which takes about 32 bytes. The map also has its bucket array: for 2 million entries at the default load factor of 0.75 it grows to 4,194,304 buckets of 4 bytes each, about 16 MB, or 8 bytes per entry.
Adding it up, one HashMap entry costs about 32 + 16 + 16 + 8 = 72 bytes, so 2 million entries take roughly 144 MB. If the SKU is a String, each key adds another 40 to 60 bytes. A TreeMap has no bucket array, but each Entry holds a key, a value, left, right and parent pointers and a colour flag, which comes to about 40 bytes, so it lands at the same 70-odd bytes per entry or more, spread over 2 million separate objects.
Two parallel arrays, a long[] of sorted SKUs and a long[] of prices at the same positions, take 8 + 8 = 16 bytes per entry, 32 MB in total, in two objects instead of 6 million. If prices fit in an int of cents, the second array drops to 8 MB.
| Structure | Lookup | Approx. memory | Refresh cost |
|---|---|---|---|
HashMap<Long, Long> | O(1) average, one or two hops | about 144 MB, 6 million objects | rebuild 6 million objects |
TreeMap<Long, Long> | O(log n), about 21 pointer hops | about 145 MB or more | rebuild plus rebalancing |
| long[] keys + long[] prices | O(log n), 21 comparisons in an array | about 32 MB, 2 objects | fill and sort two arrays |
Notice that the array version is not only smaller. The garbage collector has to trace millions of small objects in the map versions every time it marks the old generation, while two big primitive arrays contain no pointers at all and cost almost nothing to trace.
3How Each Structure Behaves on a Lookup
A HashMap lookup hashes the key, jumps to one bucket and usually compares against one node. That is one or two memory reads, but each read may land anywhere in the heap, because the node, the Long key and the Long value are separate objects. It is fast because there are so few hops.
A TreeMap lookup walks a red-black tree from the root. Each of the roughly 21 levels is a separate Entry object somewhere in the heap, so the walk is a chain of dependent pointer reads, which we call pointer chasing: the CPU cannot fetch the next node until it has read the current one. This makes TreeMap the slowest of the three for plain lookups. It earns its place only when we need ordered iteration or range queries such as subMap, headMap or ceilingKey.
A binary search over a long[] also does about 21 steps, but every step reads from one contiguous array. The first few levels of the search touch the same few positions on every lookup, so they stay in the CPU cache, and the array itself holds the values directly with no pointers to follow. The reason this matters is that a cache miss costs around 100 nanoseconds while a cached read costs about one, so locality often matters more than the O(1) versus O(log n) label.
4Building the Sorted Array Version
Here is a small, immutable table. We sort the incoming rows once, copy them into two arrays, and look up with Arrays.binarySearch, which returns the index when it finds the key and a negative number when it does not.
Notice that the class has only final fields and never changes after construction. That is what makes the refresh in the next section safe without any locks. If the source can contain the same SKU twice, we should reject or merge duplicates while building, because binary search would return either of them.
5Refreshing Every Hour Without Half-Built Data
The dangerous way to refresh is to clear the live map and refill it, or to call put() for every changed entry while readers are looking things up. Readers can then see missing prices for a few seconds, and a plain HashMap modified by one thread while others read it can even return wrong results.
The safe pattern is to build a completely new table off to the side and then publish it with one assignment to a volatile field. A volatile write makes everything written before it visible to any thread that later reads the field, so a reader either sees the whole old table or the whole new one, never a mixture. The old table becomes garbage once no reader holds it.
- Load all rows from the sourcereaders keep using the old table
- Sort and fill new arraysnothing shared is touched
- Validate the new tablerow count, no duplicates, spot checks
- Looks sane?YesAssign it to the volatile fieldNoKeep the old table and alert
- Old table becomes garbagecollected once no reader holds it
5 steps in order. Play them, or step through them one at a time.
The cost of this pattern is that both copies live in memory for a moment. With arrays, the peak is about 64 MB; with HashMap it is close to 300 MB, which is one more reason the compact layout fits this job better. The same swap works for a HashMap too, as long as nobody modifies the published map.
6Measuring Before Deciding
All the numbers above are estimates, so we confirm them. A JMH benchmark (the Java Microbenchmark Harness, which handles warm-up and dead-code elimination for us) with realistic SKUs, including misses and a random access pattern over all 2 million keys, tells us the real lookup cost. A heap histogram from jcmd <pid> GC.class_histogram after loading tells us the real memory.
There is also a middle option: a primitive collections library such as fastutil, Eclipse Collections or HPPC offers a long-to-long hash map stored in primitive arrays, around 20 to 30 bytes per entry, with O(1) lookups. That is a good choice when we want hash lookups and also need to update single entries, at the cost of a new dependency.
7Follow-up questions
How would you handle range queries over SKU prefixes?
If SKUs are strings, a sorted String[] already supports prefix queries: we binary search for the first key greater than or equal to the prefix, then scan forward while keys still start with the prefix, so the cost is O(log n + k) for k matches. A TreeMap does the same with subMap(prefix, true, prefix + Character.MAX_VALUE, false). A HashMap cannot answer range queries at all, because it does not keep keys in order. For numeric SKUs with structured prefixes, a prefix is just a numeric range, so the same lower-bound search on the long[] works.
Why not use ConcurrentHashMap for the refresh?
ConcurrentHashMap makes concurrent updates safe, but it does not make a refresh of 2 million entries atomic. Readers would see a mixture of old and new prices while we update it, and it costs even more memory per entry. Since the data changes as a whole once an hour, an immutable snapshot behind a volatile reference is simpler and gives a consistent view.
What if a lookup must also handle prices that change between refreshes?
Then we keep the hourly snapshot as the base and add a small overlay map of recent changes that is checked first, or we move to a primitive hash map that allows single-entry updates. If changes are frequent and must be seen everywhere at once, the data may belong in a shared cache or database instead of every instance's heap.
8Conclusion
In this answer, we saw that 50,000 lookups per second is a light load for any of the three structures, so memory and refresh decide the choice. A HashMap or TreeMap of boxed values costs around 70 bytes per entry and millions of objects for the garbage collector, while two sorted primitive arrays cost 16 bytes per entry and answer each lookup in about 21 cache-friendly comparisons. TreeMap is only worth it for ordered or range queries. We refresh by building a new immutable table and swapping a volatile reference, and we confirm the choice with JMH and a heap histogram.
Open with
First I would size the load: 50,000 lookups a second is tiny, even a binary search at a few hundred nanoseconds is a few percent of one core, so speed is not what decides this.
Then, if they want more
Memory is. A HashMap of boxed Long keys and values costs around 70 bytes per entry once you count the node, the two boxes and the bucket array, so about 140 MB for 2 million entries and six million objects for the GC to trace.
TreeMap is similar or worse and adds pointer chasing through about 21 levels; I would only pick it if I needed range queries or ordered iteration.
Two sorted parallel arrays, a long array of SKUs and a long or int array of prices, cost 16 bytes or less per entry, so about 32 MB, and Arrays.binarySearch finds a key in about 21 comparisons with good cache locality.
For the hourly refresh I would build a new immutable table off to the side and publish it by assigning a volatile field, so readers always see either the complete old table or the complete new one.
Then I would confirm with a JMH benchmark on realistic keys and a heap histogram, and consider a primitive hash map from fastutil if we also needed single-entry updates.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the official documentation for the version you use. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "A service looks up product prices by SKU 50,000 times per second. Data is 2 million...": https://scrivio-interview-library.netlify.app/java/algorithms-and-data-structures/b356d42972/