背景
今天接到一个需求,需要在之前同事写的代码基础上改动一下来完成。找到需要改动的地方写完了之后,准备自测,发现执行速度实在太慢了,才仔细看了下代码,循环里面套循环,再到最内层的循环里面一条一条的发sql去查询,算了实在看不下,改,结果就改的一发不可收拾,时间就花的有点多,后面这些基础的都改的差不多的时候,又来消灭循环,能不用循环的地方就尽量不用,然后就遇到了题目所示的问题。
代码不方便透露,就自己写了个测试代码,先讲一下大致问题,基本跟如下代码差不多
List<Object> newList = new ArrayList<>();
for (Object i : oldList) {
Object o = new Object();
BeanUtils.copyProperties(i, o);
newList.add(o);
}
复制代码
行动
当时看到这段代码的第一想法,就是为嘛不用stream流呢?可当我想到这里的时候,又在想,在这个需求里面难道stream流就真的比for循环快吗?于是就想着自己写点测试代码来试一下哪种方式更快一些,那需要的测试代码如下:
for循环代码:
private static Long forLoopMethod(List<Object> oldList){
long begin = System.currentTimeMillis();
List<Object> newList = new ArrayList<>();
for (Object i : oldList) {
Object o = new Object();
BeanUtils.copyProperties(i, o);
newList.add(o);
}
return System.currentTimeMillis() - begin;
}
复制代码
stream流方式的代码如下:
private static Long streamMethod(List<Object> oldList){
long begin = System.currentTimeMillis();
List<Object> collect = oldList.stream().map(i -> {
Object o = new Object();
BeanUtils.copyProperties(i, o);
return o;
}).collect(Collectors.toList());
return System.currentTimeMillis() - begin;
}
复制代码
测试方法:
public static void main(String[] args) {
List<Object> oldList = new ArrayList<>();
for (int i = 0; i < 1000; i++) {
oldList.add(i);
}
System.out.println("forLoopMethod花费时间:" + forLoopMethod(oldList));
System.out.println("streamMethod花费时间:" + streamMethod(oldList));
}
复制代码
测试环境:
电脑8core16thread
jdk:1.8
测试结果:
次数\方法名 | forLoopMethod | streamMethod |
---|---|---|
第1次 | 132 | 7 |
第2次 | 118 | 6 |
第3次 | 126 | 6 |
第4次 | 115 | 5 |
第5次 | 114 | 6 |
第6次 | 121 | 5 |
第7次 | 124 | 6 |
第8次 | 126 | 5 |
第9次 | 118 | 5 |
第10次 | 114 | 6 |
使用for循环平均花费时间: 120.8
使用stream流平均花费时间:5.7
结论
结论已经很清楚,在当前需求前提下,stream流比for循环速度要快得多,赶紧把项目里面给改了,帅歪歪!
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END