Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 279
Mac Avatar asked Jul 28 '13 16:07

Mac


People also ask

Which one is faster HashMap or LinkedHashMap?

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.

Is TreeMap or HashMap faster?

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.

Which offers the best performance TreeMap HashMap LinkedHashMap?

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.

Which is faster than HashMap?

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.


1 Answers

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

like image 148
Zim-Zam O'Pootertoot Avatar answered Oct 14 '22 06:10

Zim-Zam O'Pootertoot