HashMap性能测试

       HashMap是常用的容器类(集合类),遍历HashMap中的Key值,有两个方法实现:

1. 

Map map = new HashMap();
     for(Map.entry en:map.entrySet()){
         en.getKey();
}

 2.

Iterator it = map.keySet.iterator();
while(it.hasNext()){
     it.next();
}

 有的文章中说用entrySet()比keySet()的速度快,我也测试了一下,测试代码如下:

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Description HashMap性能测试
 * @author Administrator
 * 2012-9-22
 */
public class HashMapDemo {

    private static Map<String, Integer> map = new HashMap<String, Integer>();

    /**
     *  map.entrySet()
     */
    public static void testEntry() {
        map.put("a", 3);
        map.put("b", 2);
        map.put("c", 1);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 200000; i++) {
            for (Map.Entry en : map.entrySet()) {
                String s = en.getKey() + "";
            }
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }

    /**
     *  map.keySet()
     */
    public static void testKeySet() {
        map.put("a", 3);
        map.put("b", 2);
        map.put("c", 1);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 200000; i++) {
            Iterator it = map.keySet().iterator();
            while (it.hasNext()) {
                String s = it.next() + "";
            }
        }
        long end = System.currentTimeMillis();
        System.out.println(end - start);
    }
    /**
     * @param args
     */
    public static void main(String[] args) {
        //testEntry();
        testKeySet();
    } 
}

测试环境:eclipse3.3+jdk6

 测试结果,testEntry()的耗时为235,141,125,110,稳定值是125ms,testKeySet的耗时为141,125,156,109,稳定值是109ms,testKeySet()和testEntry()耗时差异不大, keySet() 比entrySet()反而略快一些。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值