Java map存数据效率_java性能优化之HashMap,LinkedHashMap,TreeMap读取大量数据效率的比较...

很多时候,我们用jdbctemplate或mybatis的时候,为了查询通用,会选择使用map数据结构,因为hashmap本身无序,所以为了保证key的有序性,会采用linkedhashmap。所以我们要看一下Linkedhashmap的性能影响多大。如下:

@Test

public void test() {

Integer count =1000000;

Random random =new Random();

Map map = new HashMap();

for (int i = 0; i < count; i++) {

map.put(i+"", i+"");

}

long time1 = System.currentTimeMillis();

for (int i = 0; i < count; i++) {

map.get((random.nextInt(count)+1)+"");

}

long time2 = System.currentTimeMillis();

System.out.println("HashMap time:" + (time2 - time1));

Map linkedMap = new LinkedHashMap();

for (int i = 0; i < count; i++) {

linkedMap.put(i+"", i+"");

}

time1 = System.currentTimeMillis();

for (int i = 0; i < count; i++) {

linkedMap.get((random.nextInt(count)+1)+"");

}

time2 = System.currentTimeMillis();

System.out.println("LinkedHashMap time:" + (time2 - time1));

Map treeMap = new TreeMap();

for (int i = 0; i < count; i++) {

treeMap.put(i+"", i+"");

}

time1 = System.currentTimeMillis();

for (int i = 0; i < count; i++) {

treeMap.get((random.nextInt(count)+1)+"");

}

time2 = System.currentTimeMillis();

System.out.println("TreeMap time:" + (time2 - time1));

}

执行结果:

HashMap time:641

LinkedHashMap time:703

TreeMap time:4040

读取数据是有序,则如下:

@Test

public void test2() {

Integer count =1000000;

Random random =new Random();

Map map = new HashMap();

for (int i = 0; i < count; i++) {

map.put(i+"", i+"");

}

long time1 = System.currentTimeMillis();

for (int i = 0; i < count; i++) {

map.get(i+"");

}

long time2 = System.currentTimeMillis();

System.out.println("HashMap time:" + (time2 - time1));

Map linkedMap = new LinkedHashMap();

for (int i = 0; i < count; i++) {

linkedMap.put(i+"", i+"");

}

time1 = System.currentTimeMillis();

for (int i = 0; i < count; i++) {

linkedMap.get(i+"");

}

time2 = System.currentTimeMillis();

System.out.println("LinkedHashMap time:" + (time2 - time1));

Map treeMap = new TreeMap();

for (int i = 0; i < count; i++) {

treeMap.put(i+"", i+"");

}

time1 = System.currentTimeMillis();

for (int i = 0; i < count; i++) {

treeMap.get(i+"");

}

time2 = System.currentTimeMillis();

System.out.println("TreeMap time:" + (time2 - time1));

}

HashMap time:297

LinkedHashMap time:203

TreeMap time:438

从上可知,LinkedHashMap是可以完全代替HashMap的,不用担心性能问题。

标签:count,time1,java,HashMap,int,System,time2,TreeMap,++

来源: https://www.cnblogs.com/zhjh256/p/11626524.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值