java map随机取值_HashMap随机取值和迭代器取值的对比

一共四中方法,前两种是迭代器取值,后两种是随机取值,循环了5000万次,时间分别为:迭代器读取的速度大约是随机读取的速度的1.5倍,数据量越大,差距越明显。

另外,插入是读取的100倍左右的时间(这个判定只是个大概参考)。

48138(插入)

403(迭代器读取)

400(迭代器读取)

653(随机读取)

561(随机读取)

package main;

import java.util.HashMap;

import java.util.Iterator;

import java.util.Map;

import java.util.Map.Entry;

public class test {

public static void main(String[] args) {

int mapCount = 50000000;

String tmp = "";

Map testMap = new HashMap<>();

String testValue = "";

Long startTime0 = System.currentTimeMillis();

for(int i = 1;i

tmp = testMap.put(i, testValue);

}

Long endTime0 = System.currentTimeMillis();

System.out.println(endTime0-startTime0);

Long startTime1 = System.currentTimeMillis();

for(Entry entry : testMap.entrySet()){

tmp = entry.getValue();

}

Long endTime1 = System.currentTimeMillis();

System.out.println(endTime1-startTime1);

Long startTime2 = System.currentTimeMillis();

Iterator> it = testMap.entrySet().iterator();

while(it.hasNext()){

tmp = it.next().getValue();

}

Long endTime2 = System.currentTimeMillis();

System.out.println(endTime2-startTime2);

Long startTime3 = System.currentTimeMillis();

for(Integer i : testMap.keySet()){

tmp = testMap.get(i);

}

Long endTime3 = System.currentTimeMillis();

System.out.println(endTime3-startTime3);

Long startTime4 = System.currentTimeMillis();

for(Entry entry : testMap.entrySet()){

tmp = testMap.get(entry.getKey());

}

Long endTime4 = System.currentTimeMillis();

System.out.println(endTime4-startTime4);

}

}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值