TreeMap或HashMap更快

这个问题在这里已经有了答案:

  • HashMap,LinkedHashMap和TreeMap之间的区别16个答案
  • HashMap和TreeMap有什么区别? [复制] 8个答案

  • 考虑到没有多少混合,hashmaps会给你o(1)的表现(有很多的混合,这可能会降级到潜在的O(n),其中N是任何单个桶中的条目数量(colissions))。 另一方面,如果您想要某种平衡的树结构,可以产生O(logN)检索,则使用TreeMaps。 所以这取决于你的特定用例。 但是,如果你只是想访问元素,不管他们的顺序使用HashMap


    public class MapsInvestigation {
    
    public static HashMap<String, String> hashMap = new HashMap<String, String>();
    public static TreeMap<String, String> treeMap = new TreeMap<String, String>();
    public static ArrayList<String> list = new ArrayList<String>();
    
    static {
        for (int i = 0; i < 10000; i++) {
            list.add(Integer.toString(i, 16));
        }
    }
    
    
    public static void main(String[] args) {
        System.out.println("Warmup populate");
        for (int i = 0; i < 1000; i++) {
            populateSet(hashMap);
            populateSet(treeMap);
        }
        measureTimeToPopulate(hashMap, "HashMap", 1000);
        measureTimeToPopulate(treeMap, "TreeMap", 1000);
    
        System.out.println("Warmup get");
        for (int i = 0; i < 1000; i++) {
            get(hashMap);
            get(treeMap);
        }
        measureTimeToContains(hashMap, "HashMap", 1000);
        measureTimeToContains(treeMap, "TreeMap", 1000);
    
    }
    
    private static void get(Map<String, String> map) {
        for (String s : list) {
            map.get(s);
        }
    
    }
    
    private static void populateSet(Map<String, String> map) {
        map.clear();
        for (String s : list) {
            map.put(s, s);
        }
    
    }
    
    
    private static void measureTimeToPopulate(Map<String, String> map, String setName, int reps) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < reps; i++) {
            populateSet(map);
        }
        long finish = System.currentTimeMillis();
        System.out.println("Time to populate " + (reps * map.size()) + " entries in a " + setName + ": " + (finish - start));
    }
    
    private static void measureTimeToContains(Map<String, String> map, String setName, int reps) {
        long start = System.currentTimeMillis();
        for (int i = 0; i < reps; i++) {
            get(map);
        }
        long finish = System.currentTimeMillis();
        System.out.println("Time to get() " + (reps * map.size()) + " entries in a " + setName + ": " + (finish - start));
    }
    }
    

    给出这些结果:

    Warmup populate
    Time to populate 10000000 entries in a HashMap: 230
    Time to populate 10000000 entries in a TreeMap: 1995
    Warmup get
    Time to get() 10000000 entries in a HashMap: 140
    Time to get() 10000000 entries in a TreeMap: 1164
    

    HashMap是O(1)(通常)用于访问; TreeMap是O(log n)(有保证)。

    这假设你的关键对象是不可变的,并且有正确的equals和hashCode方法。 有关如何正确覆盖equals和hashCode,请参阅Joshua Bloch的“Effective Java”第3章。

    链接地址: http://www.djcxy.com/p/92171.html

    上一篇: TreeMap or HashMap faster

    下一篇: TreeMap or HashMap?