首页 > 解决方案 > 是什么让 Hashmap.putIfAbsent 比 containsKey 和 put 快?

问题描述

问题

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

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

 if(!map.containsKey(x)){ 
   map.put(x,someValue); 
}

我以前认为 putIfAbsent 是调用 containsKey 后跟 HashMap 上的 put 的便捷方法。但是在运行基准测试之后 putIfAbsent 比使用 containsKey 后跟 Put 快得多。我查看了 java.util 源代码以尝试了解这是如何实现的,但这对我来说有点太神秘了,无法弄清楚。有谁在内部知道 putIfAbsent 似乎如何以更好的时间复杂度工作?这是我基于运行一些代码测试的假设,其中我的代码在使用 putIfAbsent 时运行速度提高了 50%。似乎避免调用 get() 但如何?

例子

if(!map.containsKey(x)){
     map.put(x,someValue);
}

VS

map.putIfAbsent(x,somevalue)

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

标签: javacollectionshashmap

解决方案


只搜索一次键的HashMap实现putIfAbsent,如果没有找到键,则将值放入相关的 bin(已经找到)中。就是putVal这样。

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

注意put也调用putValputcalls putVal(hash(key), key, value, false, true)while putIfAbsentcalls putVal(hash(key), key, value, true, true)),所以putIfAbsent和调用just的性能一样put,比同时调用containsKeyand要快put


推荐阅读