http://www.trinea.cn/android/hashmap-loop-performance/

************************************************************

主要介绍HashMap的四种循环遍历方式,各种方式的性能测试对比,根据HashMap的源码实现分析性能结果,总结结论

1. Map的四种遍历方式

下面只是简单介绍各种遍历示例(以HashMap为例),各自优劣会在本文后面进行分析给出结论。

(1) for each map.entrySet()

Java
Map<String, String> map = new HashMap<String, String>();
for (Entry<String, String> entry : map.entrySet()) {
entry.getKey();
entry.getValue();
}
1
2
3
4
5
Map<String, String> map = new HashMap<String, String>();
for (Entry<String, String> entry : map.entrySet()) {
entry.getKey();
entry.getValue();
}

(2) 显示调用map.entrySet()的集合迭代器

Java
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
entry.getKey();
entry.getValue();
}
1
2
3
4
5
6
Iterator<Map.Entry<String, String>> iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, String> entry = iterator.next();
entry.getKey();
entry.getValue();
}

(3) for each map.keySet(),再调用get获取

Java
Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
map.get(key);
}
1
2
3
4
Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
map.get(key);
}

(4) for each map.entrySet(),用临时变量保存map.entrySet()

Java
Set<Entry<String, String>> entrySet = map.entrySet();
for (Entry<String, String> entry : entrySet) {
entry.getKey();
entry.getValue();
}
1
2
3
4
5
Set<Entry<String, String>> entrySet = map.entrySet();
for (Entry<String, String> entry : entrySet) {
entry.getKey();
entry.getValue();
}

在测试前大家可以根据对HashMap的了解,想想上面四种遍历方式哪个性能更优。

2、HashMap四种遍历方式的性能测试及对比

以下是性能测试代码,会输出不同数量级大小的HashMap各种遍历方式所花费的时间。

HashMap循环遍历方式性能对比测试代码

PS:如果运行报异常in thread “main” java.lang.OutOfMemoryError: Java heap space,请将main函数里面map size的大小减小。

其中getHashMaps函数会返回不同size的HashMap。

loopMapCompare函数会分别用上面的遍历方式1-4去遍历每一个map数组(包含不同大小HashMap)中的HashMap。

print开头函数为输出辅助函数,可忽略。

测试环境为Windows7 32位系统 3.2G双核CPU 4G内存,Java 7,Eclipse -Xms512m -Xmx512m

最终测试结果如下:

Java
compare loop performance of HashMap
-----------------------------------------------------------------------
map size | 10,000 | 100,000 | 1,000,000 | 2,000,000
-----------------------------------------------------------------------
for each entrySet | 2 ms | 6 ms | 36 ms | 91 ms
-----------------------------------------------------------------------
for iterator entrySet | 0 ms | 4 ms | 35 ms | 89 ms
-----------------------------------------------------------------------
for each keySet | 1 ms | 6 ms | 48 ms | 126 ms
-----------------------------------------------------------------------
for entrySet=entrySet()| 1 ms | 4 ms | 35 ms | 92 ms
-----------------------------------------------------------------------
1
2
3
4
5
6
7
8
9
10
11
12
compare loop performance of HashMap
-----------------------------------------------------------------------
map size               | 10,000    | 100,000   | 1,000,000 | 2,000,000
-----------------------------------------------------------------------
for each entrySet      | 2 ms      | 6 ms      | 36 ms     | 91 ms    
-----------------------------------------------------------------------
for iterator entrySet  | 0 ms      | 4 ms      | 35 ms     | 89 ms    
-----------------------------------------------------------------------
for each keySet        | 1 ms      | 6 ms      | 48 ms     | 126 ms    
-----------------------------------------------------------------------
for entrySet=entrySet()| 1 ms      | 4 ms      | 35 ms     | 92 ms    
-----------------------------------------------------------------------

表横向为同一遍历方式不同大小HashMap遍历的时间消耗,纵向为同一HashMap不同遍历方式遍历的时间消耗。

PS:由于首次遍历HashMap会稍微多耗时一点,for each的结果稍微有点偏差,将测试代码中的几个Type顺序调换会发现,for each entrySet耗时和for iterator entrySet接近。

3、遍历方式性能测试结果分析

(1) foreach介绍

见:ArrayList和LinkedList的几种循环遍历方式及性能对比分析中介绍。

(2) HashMap遍历方式结果分析

从上面知道for each与显示调用Iterator等价,上表的结果中可以看出除了第三种方式(for each
map.keySet()),再调用get获取方式外,其他三种方式性能相当。本例还是hash值散列较好的情况,若散列算法较差,第三种方式会更加耗时。

我们看看HashMap entrySet和keySet的源码

Java
private final class KeyIterator extends HashIterator<K> {
public K next() {
return nextEntry().getKey();
}
}

private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
public Map.Entry<K,V> next() {
return nextEntry();
}
}

1
2
3
4
5
6
7
8
9
10
11
private final class KeyIterator extends HashIterator<K> {
public K next() {
return nextEntry().getKey();
}
}
 
private final class EntryIterator extends HashIterator<Map.Entry<K,V>> {
public Map.Entry<K,V> next() {
return nextEntry();
}
}

分别是keySet()和entrySet()返回的set的迭代器,从中我们可以看到只是返回值不同而已,父类相同,所以性能相差不多。只是第三种方式多了一步根据key get得到value的操作而已。get的时间复杂度根据hash算法而异,源码如下:

Java
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);

return null == entry ? null : entry.getValue();
}

/**
* Returns the entry associated with the specified key in the
* HashMap. Returns null if the HashMap contains no mapping
* for the key.
*/
final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key);
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 != null && key.equals(k))))
return e;
}
return null;
}

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public V get(Object key) {
if (key == null)
return getForNullKey();
Entry<K,V> entry = getEntry(key);
 
return null == entry ? null : entry.getValue();
}
 
/**
* Returns the entry associated with the specified key in the
* HashMap.  Returns null if the HashMap contains no mapping
* for the key.
*/
final Entry<K,V> getEntry(Object key) {
int hash = (key == null) ? 0 : hash(key);
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 != null && key.equals(k))))
return e;
}
return null;
}

get的时间复杂度取决于for循环循环次数,即hash算法。

4、结论总结

从上面的分析来看:

a. HashMap的循环,如果既需要key也需要value,直接用

Java
Map<String, String> map = new HashMap<String, String>();
for (Entry<String, String> entry : map.entrySet()) {
entry.getKey();
entry.getValue();
}
1
2
3
4
5
Map<String, String> map = new HashMap<String, String>();
for (Entry<String, String> entry : map.entrySet()) {
entry.getKey();
entry.getValue();
}

即可,foreach简洁易懂。

b. 如果只是遍历key而无需value的话,可以直接用

Java
Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
// key process
}
1
2
3
4
Map<String, String> map = new HashMap<String, String>();
for (String key : map.keySet()) {
// key process
}
 
 

HashMap循环遍历方式及其性能对比(zhuan)的更多相关文章

  1. HashMap循环遍历方式及其性能对比

    主要介绍HashMap的四种循环遍历方式,各种方式的性能测试对比,根据HashMap的源码实现分析性能结果,总结结论.   1. Map的四种遍历方式 下面只是简单介绍各种遍历示例(以HashMap为 ...

  2. ArrayList和LinkedList的几种循环遍历方式及性能对比分析(转)

    主要介绍ArrayList和LinkedList这两种list的五种循环遍历方式,各种方式的性能测试对比,根据ArrayList和LinkedList的源码实现分析性能结果,总结结论. 通过本文你可以 ...

  3. ArrayList和LinkedList的几种循环遍历方式及性能对比分析(转载)

    原文地址: http://www.trinea.cn/android/arraylist-linkedlist-loop-performance/ 原文地址: http://www.trinea.cn ...

  4. 【转】ArrayList和LinkedList的几种循环遍历方式及性能对比分析

    原文网址:http://www.trinea.cn/android/arraylist-linkedlist-loop-performance/ 主要介绍ArrayList和LinkedList这两种 ...

  5. Java 集合 ArrayList和LinkedList的几种循环遍历方式及性能对比分析 [ 转载 ]

    Java 集合 ArrayList和LinkedList的几种循环遍历方式及性能对比分析 @author Trinea 原文链接:http://www.trinea.cn/android/arrayl ...

  6. (转)ArrayList和LinkedList的几种循环遍历方式及性能对比分析

    主要介绍ArrayList和LinkedList这两种list的五种循环遍历方式,各种方式的性能测试对比,根据ArrayList和LinkedList的源码实现分析性能结果,总结结论. 通过本文你可以 ...

  7. ArrayList和LinkedList的几种循环遍历方式及性能对比分析

    最新最准确内容建议直接访问原文:ArrayList和LinkedList的几种循环遍历方式及性能对比分析 主要介绍ArrayList和LinkedList这两种list的五种循环遍历方式,各种方式的性 ...

  8. ArrayList和LinkedList遍历方式及性能对比分析

    ArrayList和LinkedList的几种循环遍历方式及性能对比分析 主要介绍ArrayList和LinkedList这两种list的五种循环遍历方式,各种方式的性能测试对比,根据ArrayLis ...

  9. JS几种数组遍历方式以及性能分析对比

    前言 这一篇与上一篇 JS几种变量交换方式以及性能分析对比 属于同一个系列,本文继续分析JS中几种常用的数组遍历方式以及各自的性能对比 起由 在上一次分析了JS几种常用变量交换方式以及各自性能后,觉得 ...

随机推荐

  1. Oracle插入时间

    现象:Oracle 插入时间时 ,报错:ORA-01861: 文字与格式字符串不匹配 解决方法: 这个错误一般出现在时间字段上,即你插入的时间格式和数据库现有的时间格式不一致,解决的方法是格式化你 插 ...

  2. hrtimer和work工作队列的使用

    1.hrtimers - 为高分辨率kernel定时器,可作为超时或周期性定时器使用 1). hrtimer_init初始化定时器工作模式. hrtimer_init(&vibe_timer, ...

  3. 制作变形、移位、扭曲等效果:《CSS3 transform》

    今天开始我们一起来学习有关于CSS3制作动画的几个属性:变形(transform).转换(transition)和动画(animation)等更高级的CSS3技术.本文主要介绍的是这三个属性之中的第一 ...

  4. thinkphp隐藏中url的index.php

    在本地进行测试 1.修改apache配置文件将如下代码#去掉 #LoadModule rewrite_module modules/mod_rewrite.so   在index.php 目录下新建文 ...

  5. hnu Dirichlet's Theorem

    /* 求ax+b x属于区间[L,R];范围内素数的个数. a*R+b<=10^12 ; R-L+1<=10^6 枚举,超时. 1.如果GCD(a,b)>1 那么a+b 2*a+b ...

  6. Mybatis like 模糊查询问题

    1.mysql:LIKE CONCAT('%',#{empname},'%' ) 或者 LIKE CONCAT('%',‘${empname}’,'%' ) 2.oracle:LIKE '%'||#{ ...

  7. program

    [题目分析] 题目的意思是在一个数列中找到四个数,a[i]=a[j]<a[k]=a[l],其他都扯淡. 先把这些数sort一下,所有相等的数字就都排在一起了,然后这个数列可以按照数字的种类划分成 ...

  8. 专题:php页面跳转方法

    php只有一种方法,利用JavaScript的window.location[和window.location.href效果相同]是一种方法,利用html的meta的Refresh是一种方法. 代码 ...

  9. Python使用requirements.txt安装类库

    摘要:我们为何要应用requirements.txt呢? 首要应用目标: 任何 运用顺序 平常 须要设置装置 所需并 依附 一组类库去知足 事情请求 . 请求 文件 是 指定 战 一次性 装置 包 的 ...

  10. FZU 2214 Knapsack problem(背包问题)

    Description 题目描述 Given a set of n items, each with a weight w[i] and a value v[i], determine a way t ...