Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Performance of TreeMap, HashMap and LinkedHashMap?

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?

like image 218
Vicky Avatar asked May 04 '12 04:05

Vicky


People also ask

Which is faster HashMap or LinkedHashMap TreeMap?

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

What is the difference between LinkedHashMap TreeMap and HashMap?

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.

Is TreeMap better than HashMap?

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


1 Answers

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.

Edit:

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);
  }
}
like image 196
Keith Randall Avatar answered Sep 18 '22 10:09

Keith Randall