HashSet与ArrayList性能测试

来源:互联网 发布:做金融好还是数据好 编辑:程序博客网 时间:2024/06/05 04:48

一、十万次循环测试,测试代码如下:
Set<Integer> set = new HashSet<>();
List<Integer> list = new ArrayList<>();
Long time1 = System.currentTimeMillis();
for(int i = 0; i < 100000; i ++){
set.add(i);
}
Long time2 = System.currentTimeMillis();
for(int i = 0; i < 100000; i ++){
list.add(i);
}
Long time3 = System.currentTimeMillis();
System.out.println("set add 100000 cost:" + ( time2 - time1 ));
System.out.println("list add 100000 cost:" + ( time3 - time2 ));

Long time4 = System.currentTimeMillis();
for(Integer i : set){

}
Long time5 = System.currentTimeMillis();
Iterator<Integer> it = set.iterator();
while (it.hasNext()) {
Integer str = it.next();
}
Long time6 = System.currentTimeMillis();
for(Integer i : list){

}
Long time7 = System.currentTimeMillis();
System.out.println("set foreach iterate 100000 cost:" + ( time5 - time4 ));
System.out.println("set iterator iterate 100000 cost:" + ( time6 - time5 ));
System.out.println("list foreach iterate 100000 cost:" + ( time7 - time6 ));

结果如下:

set add 100000 cost:20
list add 100000 cost:4
set foreach iterate 100000 cost:6
set iterator iterate 100000 cost:2
list foreach iterate 100000 cost:3


set add 100000 cost:21
list add 100000 cost:3
set foreach iterate 100000 cost:4
set iterator iterate 100000 cost:4
list foreach iterate 100000 cost:3

二、五百万次循环测试,结果如下:

set add 5000000 cost:2236
list add 5000000 cost:250
set foreach iterate 5000000 cost:41
set iterator iterate 5000000 cost:40
list foreach iterate 5000000 cost:16


set add 5000000 cost:2238
list add 5000000 cost:269
set foreach iterate 5000000 cost:47
set iterator iterate 5000000 cost:39
list foreach iterate 5000000 cost:15

三、一万次循环测试,结果如下:

set add 10000 cost:5
list add 10000 cost:1
set foreach iterate 10000 cost:1
set iterator iterate 10000 cost:0
list foreach iterate 10000 cost:1


set add 10000 cost:5
list add 10000 cost:2
set foreach iterate 10000 cost:1
set iterator iterate 10000 cost:1
list foreach iterate 10000 cost:1

四、总和分析

ArrayList始终比HashSet性能要高

HashSet每次add总要判断hashcode导致效率低

HashSet两种循环中iterator 方式不稳定,不过总是比foreach要快一点

原创粉丝点击