I am writing an dictionary that make heavily use of String as key in Map<String, Index>
. What I concern is which one of HashMap
and TreeMap
will result in better (faster) performance in searching a key in the map?
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.
TreeMap Features It allows only distinct keys. Duplicate keys are not possible.
A TreeMap cannot contain duplicate keys. TreeMap cannot contain the null key. However, It can have null values.
HashMap does not maintain any insertion order of its elements hence it is quicker than Map. In contrast to Map, HashMap can hold duplicate values. It's possible to implement the Map interface by utilizing its implementing classes.
Given that there are not many collissions hashmaps will give you o(1) performance (with a lot of colissions this can degrade to potentially O(n) where N is the number of entries (colissions) in any single bucket). TreeMaps on the other hand are used if you want to have some sort of balanced tree structure which yields O(logN) retrieval. So it really depends on your particular use-case. But if you just want to access elements, irrespective of their order use HashMap
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