Search code examples
javacollectionsiteration

HashMap or TreeMap or LinkedHashMap which one is fastest to iterate over?


I have a Map which is filled up during the start up of application. It doesn't change later during the execution of application. Later this map is only used to iterate all the elements in it. Which concrete implementation of Map should I choose? HashMap or TreeMap or LinkedHashMap ?
UPDATE
Insertion order doesn't matter. The only thing that matters is fast iteration of all elements (say 6000 elements).


Solution

  • None of the other answers here take into consideration the effects of the CPU cache, which can be huge when iteration is concerned.

    One way to improve this is to use just a single array of interleaved keys and values (keys at even indices, values at odd ones). This will tightly group together these data items and maximally leverage the cache, at least for the references.

    But the true, screaming improvement would be achieved if you could avoid creating objects which hold your data and use just arrays of primitive values. This is, naturally, highly dependent on your use case.