Java8的流式计算对比普通计算
import java.util.stream.LongStream; public class Test { public static void main(String[] args) { // 普通方法 Long sumCount1 = 0L; long start1 = System.currentTimeMillis(); for (Long i = 0L; i <= 60_000_000L; i++) { sumCount1 += i; } long end1 = System.currentTimeMillis(); System.out.println("普通方法总和为=" + sumCount1 + ",用时:" + (end1 - start1) + "毫秒。"); // 流式计算 long start2 = System.currentTimeMillis(); long sumCount2 = LongStream.rangeClosed(0L, 60_000_000L).parallel().reduce(0L, Long::sum); long end2 = System.currentTimeMillis(); System.out.println("流式方法总和为=" + sumCount2 + ",用时:" + (end2 - start2) + "毫秒。"); } }
结果
普通方法总和为=1800000030000000,用时:689毫秒。
流式方法总和为=1800000030000000,用时:98毫秒。