![85793afe64a7a7f69469b1840a804ab9.png](https://img-blog.csdnimg.cn/img_convert/85793afe64a7a7f69469b1840a804ab9.png)
发现了JAVA8新出的循环方式后, 我觉得我终于可以摆脱掉老掉牙的for了~
但是每个类都有自己的应用场景, 不要为了让代码看起来炫酷而丧失编码的本质~
一切都要为了性能~
下段代码对 [ for, IntStream.forEach, IntStream.parallel.forEach ]进行了性能对比.
public void executeTime() {
StopWatch stopWatch = new StopWatch("ExecuteTime");
stopWatch.start("ExecuteTimeByFor");
//普通for循环
for (int i = 0; i < 100; i++) {
try {
System.out.println(i);
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stopWatch.stop();
stopWatch.start("ExecuteTimeByIntStream");
//stream串行流
IntStream.range(0, 100).forEach(
i -> {
try {
System.out.println(i);
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
);
stopWatch.stop();
stopWatch.start("ExecuteTimeByIntStreamParallel");
//stream并行流
IntStream.range(0, 100).parallel().forEach(
i -> {
try {
System.out.println(i);
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
);
stopWatch.stop();
System.out.println(stopWatch.prettyPrint());
}
打印输出:
- ExecuteTimeByFor:0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15...95.96.97.98.99.[1]
- ExecuteTimeByIntStream:0.1.2.3.4.5.6.7.8.9.10.11.12.13.14.15...95.96.97.98.99.[2]
- ExecuteTimeByIntStreamParallel:65.66.67.32.90.33.63.91.92.31.64.62.35.88.36.89...53.51.54.52.55.[3]
耗时输出:
StopWatch 'ExecuteTime': running time (millis) = 360
-----------------------------------------
ms % Task name
-----------------------------------------
00153 042% ExecuteTimeByFor
00176 049% ExecuteTimeByIntStream
00031 009% ExecuteTimeByIntStreamParallel
总结:
可见for与IntStream.forEach性能方面并没有什么区别,并且是按序输出.
而IntStream.parallel.forEach由于并行执行,性能提升数倍,但是是乱序输出,并不适合按序执行的场景.
参考
- ^有序
- ^有序
- ^无序