In TreeMap - Elements are sorted
In HashMap - Elements are not sorted
So, if I consider get
, put
and remove
methods which map should I use for performance?
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.
Operations such as adding, removing, or finding entries based on a key are constant time, as they hash the key. So adding, removing, and finding entries in a LinkedHashMap can be slightly slower than in a HashMap because it maintains a doubly-linked list of Buckets in Java.
Use LinkedHashMap, if you need to maintain insertion or access order of mappings like in LRU Cache. Use TreeMap, if you need to maintain mappings in sorted order, either in their natural order or a custom order defined by Comparator, and use HashMap for all your general-purpose hashing-based collection requirements.
HashMap is faster than TreeMap because it provides constant-time performance that is O(1) for the basic operations like get() and put(). TreeMap is slow in comparison to HashMap because it provides the performance of O(log(n)) for most operations like add(), remove() and contains().
Use a HashMap
unless you have some need for ordering. HashMap
is faster.
That said, you can make it easy to switch by using the generic interface as your declaration:
Map<String,String> M = new HashMap<String,String>();
...use M lots of places...
Then all you have to do is switch one place and your code uses the new map type.
A simple timing test:
import java.util.*;
class TimingTest {
public static void main(String[] args) {
Map<String,String> M = new HashMap<String,String>();
long start = System.currentTimeMillis();
for (int i = 0; i < 100000; i++) {
M.put(Integer.toString(i), "foo");
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}
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