是什么让Hashmap.putIfAbsent比containsKey更快,然后是put?

Usm*_*kil 7 java collections hashmap

HashMap方法putIfAbsent如何以比调用containsKey(x)之前更快的方式有条件地执行put?

例如,如果您没有使用putIfAbsent,则可以使用:

 if(!map.containsKey(x)){ 
   map.put(x,someValue); 
}
Run Code Online (Sandbox Code Playgroud)

我以前认为putIfAbsent是调用containsKey然后放在HashMap上的方便方法.但在运行基准测试后,putIfAbsent明显快于使用containsKey后跟Put.我查看了java.util源代码,试着看看这是怎么回事,但是对我来说有点太神秘了.有没有人知道putIfAbsent似乎在更好的时间复杂度下工作?这是我的假设基于运行一些代码测试,其中我的代码在使用putIfAbsent时运行速度提高了50%.它似乎避免调用get()但如何?

if(!map.containsKey(x)){
     map.put(x,someValue);
}
Run Code Online (Sandbox Code Playgroud)

VS

map.putIfAbsent(x,somevalue)
Run Code Online (Sandbox Code Playgroud)

Hashmap.putIfAbsent的Java源代码

@Override
public V putIfAbsent(K key, V value) {
    return putVal(hash(key), key, value, true, true);
}

final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        else {
            for (int binCount = 0; ; ++binCount) {
                if ((e = p.next) == null) {
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    break;
                }
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    break;
                p = e;
            }
        }
        if (e != null) { // existing mapping for key
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}
Run Code Online (Sandbox Code Playgroud)

Era*_*ran 9

HashMap执行putIfAbsent一次密钥搜索的实现,如果找不到密钥,则将值放入相关的bin(已经找到)中.这是什么putVal.

另一方面,使用map.containsKey(x)后跟map.put(x,someValue)对其中的键执行两次查找Map,这需要更多时间.

需要注意的是put还呼吁putVal(put电话putVal(hash(key), key, value, false, true)同时putIfAbsent通话putVal(hash(key), key, value, true, true)),所以putIfAbsent具有相同的性能与调用只是put,这比调用速度更快containsKeyput.