为什么创建哈希映射比创建对象更快[]?

2022-09-01 01:01:51

我试图构建自己的Map来提高特殊环境的性能,我意识到了一件非常有趣的事情:创建a比 - 无论我以什么顺序执行这些命令都要快。这对我来说非常令人困惑,特别是因为哈希映射构造函数包含一个,根据这个。我的测试平台有问题吗?new Hashmap<Integer,String>(2000)new Object[2000]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
}

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


答案 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() {
}

所以实际上并不习惯创建数组。它在哪里使用?看看方法。initialCapacityput()

public V put(K key, V value) {
    if (table == EMPTY_TABLE) {
        inflateTable(threshold);
    }
    // hidden
} 

执行看跌期权时,数组实际上是创建的。我没有显示,但它做了一些数学运算并初始化数组。inflateTable()


答案 2

空对象比包含 2000 个引用的数组小得多。即使您将 2000 传递给构造函数的参数,它实际上还没有为对象创建 2000 个空格。HashMapObjectinitialCapacityHashMap