为什么创建HashMap比创建Object []更快?

时间:2015-07-14 23:20:39

标签: java arrays performance hashmap

我尝试构建自己的Map以提高特殊环境的性能,我意识到一些非常有趣的事情:创建new Hashmap<Integer,String>(2000)new Object[2000]更快 - 无论我在哪个顺序执行这些命令。这对我来说非常困惑,尤其是。因为根据this,Hashmap构造函数包含table = new Entry[capacity]。我的测试平台有问题吗?

public static void test(int amm){ //amm=1_000_000
    Map<Integer,String> m1 = null;
    Object[] arr = null;

    long time = System.nanoTime();
    for(int i = 0; i < amm; i++){
        m1 = new HashMap<Integer, String>(2000);
    }
    System.out.println("m1: " + (System.nanoTime() - time)); //m1: 70_455_065

    time = System.nanoTime();
    for(int i = 0; i < amm; i++){
        arr = new Object[2000];
    }
    System.out.println("arr: " + (System.nanoTime() - time)); //arr: 1_322_473_803
}

我很想看到另一台计算机上的测试结果。我不知道为什么创建HashMap比创建Object[]快10倍。

2 个答案:

答案 0 :(得分:51)

如果查看channel.basicQos(1);的实现,构造函数如下所示:

HashMap

public HashMap(int initialCapacity, float loadFactor) { if (initialCapacity < 0) throw new IllegalArgumentException("Illegal initial capacity: " + initialCapacity); if (initialCapacity > MAXIMUM_CAPACITY) initialCapacity = MAXIMUM_CAPACITY; if (loadFactor <= 0 || Float.isNaN(loadFactor)) throw new IllegalArgumentException("Illegal load factor: " + loadFactor); this.loadFactor = loadFactor; threshold = initialCapacity; init(); } 看起来像:

init()

因此/** * Initialization hook for subclasses. This method is called * in all constructors and pseudo-constructors (clone, readObject) * after HashMap has been initialized but before any entries have * been inserted. (In the absence of this method, readObject would * require explicit knowledge of subclasses.) */ void init() { } 实际上并不习惯于创建数组。它在哪里使用?查看initialCapacity方法。

put()

执行put时,实际创建了数组。我没有显示public V put(K key, V value) { if (table == EMPTY_TABLE) { inflateTable(threshold); } // hidden } ,但它做了一些数学运算并初始化了数组。

答案 1 :(得分:21)

HashMap对象远小于2000 Object个引用的数组。即使您将2000传递给initialCapacity构造函数的HashMap参数,它实际上也没有为对象创建2000个空格。