测试一下for i、foreach、lamda list.forEach、lamda list.parallelStream().forEach的效率,对比一下哪个更快。
遍历集合
设计一个大小为10000的集合,通过各种类型的for循环遍历一遍,查看时长
long time0 = System.currentTimeMillis();
for (String str : list) {
str.toString();
}
System.out.println("foreach: " + (time1 - time0));
for (int i = 0; i < n; i++) {
list.get(i).toString();
}
long time2 = System.currentTimeMillis();
System.out.println("for i: " + (time2 - time1));
list.forEach(str -> {
str.toString();
});
long time3 = System.currentTimeMillis();
System.out.println("lamda foreach:" + (time3 - time2));
list.parallelStream().forEach(str -> {
str.toString();
});
System.out.println("lamda stream foreach: " + (System.currentTimeMillis() - time3));
运行结果:
foreach: 2
for i: 1
lamda foreach:54
lamda stream foreach: 6
foreach和for i是差不多的,list.parallelStream().forEach稍微慢一点,list.forEach是最慢的,猜想是因为lamda表达式调用了list的forEach方法,而不是只遍历了迭代器,parallelStream相对来说稍微快一点,网上有说是因为stream这种其实是多线程实现的。下面来试一下
遍历集合并做某些事情
由于要进行休眠,我们将数组大小调整为100,每次休眠10ms
long time0 = System.currentTimeMillis();
for (String str : list) {
str.toString();
Thread.sleep(10L);
}
System.out.println("foreach: " + (time1 - time0));
for (int i = 0; i < n; i++) {
list.get(i).toString();
Thread.sleep(10L);
}
long time2 = System.currentTimeMillis();
System.out.println("for i: " + (time2 - time1));
list.forEach(str -> {
str.toString();
Thread.sleep(10L);
});
long time3 = System.currentTimeMillis();
System.out.println("lamda foreach:" + (time3 - time2));
list.parallelStream().forEach(str -> {
str.toString();
Thread.sleep(10L);
});
System.out.println("lamda stream foreach: " + (System.currentTimeMillis() - time3));
运行结果:
foreach: 1610
for i: 1635
lamda foreach:1736
lamda stream foreach: 223
parallelStream连1000ms都没有,应该是多个线程一起跑没差了。
同时看到lamda表达式中的forEach与传统的遍历方法相差不大了。遍历迭代器的方式比for i的方式一直都快一点点