测试代码
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循环