题
HashMap方法putIfAbsent如何以比调用containsKey(x)之前更快的方式有条件地执行put?
例如,如果您没有使用putIfAbsent,则可以使用:
if(!map.containsKey(x)){ map.put(x,someValue); }
我以前认为putIfAbsent是调用containsKey然后放在HashMap上的方便方法.但在运行基准测试后,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,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,value); else { for (int binCount = 0; ; ++binCount) { if ((e = p.next) == null) { p.next = newNode(hash,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; }
解决方法
putIfAbsent的HashMap实现只搜索一次密钥,如果找不到密钥,则将值放入相关的bin(已经找到)中.这就是putVal所做的.
另一方面,使用map.containsKey(x)后跟map.put(x,someValue)对Map中的键执行两次查找,这需要更多时间.
注意put也调用putVal(put调用putVal(hash(key),false,true)而putIfAbsent调用putVal(hash(key),true)),所以putIfAbsent具有相同的性能调用just put,这比调用containsKey和put更快.