两种for循环效率比较|for x:xList和xList.forEach()
程序员文章站
2022-06-07 16:13:03
...
测试代码
public class ForTest {
public static void main(String[] args) {
ArrayList<Long> list = new ArrayList<>();
AtomicReference<Long> sum = new AtomicReference<>(0L);
for (Long i = 0L; i < 30_000_000L; i++) {
list.add(i);
}
long begin = System.currentTimeMillis();
for (Long aLong : list) {
sum.updateAndGet(v -> v + aLong);
}
System.out.println("for x:xList时间消耗:"+(System.currentTimeMillis()-begin)+" "+sum);
sum.set(0L);
begin = System.currentTimeMillis();
list.forEach((t)-> sum.updateAndGet(v -> v + t));
System.out.println("xList.forEach时间消耗:"+(System.currentTimeMillis()-begin)+" "+sum);
}
}
循环次数为3000次时:
for x:xList时间消耗:59 4498500
xList.forEach时间消耗:2 4498500
循环次数为3亿次时
for x:xList时间消耗:6222 449999985000000
xList.forEach时间消耗:366 449999985000000
可见,流式处理性能要远高于普通for循环
上一篇: PHP脚本数据库功能详解(中)_PHP