错误案例
现象描述: 在生成环境发现,偶尔生产环境的某台机器CPU使用率很高,经过定位发现是有一个大的HashMap(HashMap里面存放了大量数据,比如1W条)做循环引起的。
错误分析
遍历一个HashMap
for(Iterator ite = map.keySet().iterator(); ite.hasNext();){
Object key = ite.next();
Object value = map.get(key);
}
通过Map类的get(key)方法获取value时,会进行两次hashCode的计算,消耗CPU资源;而使用entrySet的方式,map对象会直接返回其保存key-value的原始数据结构对象,遍历过程无需进行错误代码中耗费时间的hashCode计算; 这在大数据量下,体现的尤为明显。
以下是HashMap.get()方法的源码:
public V get(Object key) {
if (key == null)
return getForNullKey();
int hash = hash(key.hashCode());
for (Entry<K,V> e = table[indexFor(hash, table.length)];
e!= null;
e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k)))
return e.value;
}
return null;
}
正确用法
正确用法:
for(Iterator ite = map.entrySet().iterator(); ite.hasNext();){
Map.Entry entry = (Map.Entry) ite.next();
entry.getKey();
entry.getValue();
}
本文深入分析了在大数据量下,遍历HashMap时使用get(key)方法导致的性能瓶颈,通过对比使用entrySet的方式遍历,解释了为何后者能显著减少CPU消耗。提供了正确的遍历方法实现,帮助开发者优化代码性能。
474

被折叠的 条评论
为什么被折叠?



