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).
HashMap as do not maintain any insertion order of its elements hence is faster as compare to TreeMap also do not sort its elements on the basis of its value so also faster than LinkedHashMap. LinkedHashMap is faster as compare to TreeMap but is slower than HashMap.
HashMap, being a hashtable-based implementation, internally uses an array-based data structure to organize its elements according to the hash function. HashMap provides expected constant-time performance O(1) for most operations like add(), remove() and contains(). Therefore, it's significantly faster than a TreeMap.
That is, if you need to get the keys back in insertion order, then use LinkedHashMap. If you need to get the keys back in their true/natural order, then use TreeMap. Otherwise, HashMap is probably best. It is typically faster and requires less overhead.
Performance The speed of HashSet is slower than that of HashMap. The reason that HashMap is faster than HashSet is that the HashMap uses the unique keys to access the values. It stores each value with a corresponding key and we can retrieve these values faster using keys during iteration.
HashMap
will generally be fastest, since it has the best cache behavior (HashMap
iterates directly over the backing array, whereas TreeMap
and LinkedHashMap
iterate over linked data structures).
You may want to use an ImmutableMap or UnmodifiableMap if the map isn't going to change once it's initialized
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With