码迷,mamicode.com
首页 > 其他好文 > 详细

遍历map 哪种方式更加高效。

时间:2015-06-11 00:04:06      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

 


场景:偶尔生产环境的某台机器CPU使用率很高,经过定位发现是有一个大的HashMap(HashMap里面存放了大量数据,比如1W条)做循环引起的。

代码中采用了如下的遍历

 

Java代码  技术分享
  1. for(Iterator ite = map.keySet().iterator(); ite.hasNext();){  
  2.   Object key = ite.next();  
  3.   Object value = map.get(key);  
  4. }  

 

  通过Map类的get(key)方法获取value时,会进行两次hashCode的计算,消耗CPU资源;而使用entrySet的方式,map对象会直接返回其保存key-value的原始数据结构对象,遍历过程无需进行错误代码中耗费时间的hashCode计算;这在大数据量下,体现的尤为明显。

以下是HashMap.get()方法的源码:

Java代码  技术分享
  1. public V get(Object key) {  
  2.         if (key == null)  
  3.             return getForNullKey();  
  4.         int hash = hash(key.hashCode());  
  5.         for (Entry<K,V> e = table[indexFor(hash, table.length)];  
  6.              e != null;  
  7.              e = e.next) {  
  8.             Object k;  
  9.             if (e.hash == hash && ((k = e.key) == key || key.equals(k)))  
  10.                 return e.value;  
  11.         }  
  12.         return null;  
  13.     }  

 

 

正确用法如下:

 

Java代码  技术分享
  1. for(Iterator ite = map.entrySet().iterator(); ite.hasNext();){  
  2.   Map.Entry entry = (Map.Entry) ite.next();  
  3.   entry.getKey();  
  4.   entry.getValue();  
  5. }  

 

 

对比测试

 

Java代码  技术分享
  1. public class HashMapTest {  
  2.     public static void getFromMap(Map map){  
  3.         for(Iterator ite = map.keySet().iterator(); ite.hasNext();){  
  4.             Object key = ite.next();  
  5.             Object value = map.get(key);  
  6.         }  
  7.     }  
  8.     public static void getFromMapByEntrySet(Map map){  
  9.         for(Iterator ite = map.entrySet().iterator(); ite.hasNext();){  
  10.             Map.Entry entry = (Map.Entry) ite.next();  
  11.             entry.getKey();  
  12.             entry.getValue();  
  13.         }  
  14.     }  
  15.   
  16.     public static void main(String[] args) {  
  17.         Map map = new HashMap();  
  18.         for(int i=0;i<200000;i++){  
  19.             map.put("key"+i, "value"+i);  
  20.         }  
  21.         long currentTime = System.currentTimeMillis();  
  22.         getFromMap(map);  
  23.         long currentTime2 = System.currentTimeMillis();  
  24.         getFromMapByEntrySet(map);  
  25.         long currentTime3 = System.currentTimeMillis();  
  26.         System.out.println(currentTime2-currentTime);  
  27.         System.out.println(currentTime3-currentTime2);  
  28.     }  
  29.   
  30. }  

 

运行结果:

 

 

 

Java代码  技术分享
  1. 16  
  2. 0  

 

 

经过对比,可以看到明显的差别。

还有一种最常用的遍历方法,其效果也不太好,不建议使用

 

Java代码  技术分享
  1. for(Iterator i = map.values().iterator(); i.hasNext();)   {         
  2.             Object temp =  i.next();     
  3. }    

遍历map 哪种方式更加高效。

标签:

原文地址:http://www.cnblogs.com/gtaxmjld/p/4567807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!