简体   繁体   中英

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?

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);
  }
}

It depends on how fast the hash and comparison functions are on the keys in your map. It depends on whether you're more interested in average case performance or worst-case performance. It depends on whether you have a good hash function applied to your map's keys; hash values should be well distributed across the hash function's domain (yes, it can depend on your data).

In general (when you can't be bothered to test), a hash map is often a good answer, but it's also unlikely to make a big difference if you don't have a thousands of entries (for small sizes, a "vec map" can also work well).

It depends on your intentions, in terms of iteration:

  • The HashMap makes no guarentee of such, wich means its random;
  • The TreeMap uses natural order or a Comparator if specified;
  • The LinkedHashMap is iterated according to insertion order.

Futhermore, for TimeComplexity for put/get/remove/containsKey:

  • HashSet - O(1);
  • TreeMap - O(log(n)) or O(1); -- see references!
  • LinkedHashSet - O(1).

Geekforgeeks:

StackOverflow:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM