java - 是什么让 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;
}
解决方案
只搜索一次键的HashMap
实现putIfAbsent
,如果没有找到键,则将值放入相关的 bin(已经找到)中。就是putVal
这样。
另一方面,使用map.containsKey(x)
后跟map.put(x,someValue)
对 中的键执行两次查找Map
,这需要更多时间。
注意put
也调用putVal
(put
calls putVal(hash(key), key, value, false, true)
while putIfAbsent
calls putVal(hash(key), key, value, true, true)
),所以putIfAbsent
和调用just的性能一样put
,比同时调用containsKey
and要快put
。
推荐阅读
- python - while 和 for 循环有什么区别
- arrays - 将字符串数组快速转换为 C 字符串的 C 数组不起作用
- javascript - 为什么我在使用 jQuery 和 JavaScript 时得到不同的结果
- laravel - 如何在 Chartisan 中制作堆积条形图
- java - 主页按钮按下后不起作用
- reactjs - 顺风css中的自定义字体大小在reactjs storybookjs中不起作用
- html - XHTML - 在现代应用程序开发中使用 xhtml 有什么好处?
- .net - .Net 具有十六进制地址的多行正则表达式
- docker - docker-compose down 和 docker-compose kill 有什么区别?
- javascript - 元素未在反应状态上添加数组