第六章:并行数据处理与性能
并行流
假如你需要写一个方法,接受数字 n 作为参数,并返回从1到给定参数的所有数字的和。
public class DemoTest { public static void main(String[] args) { // 测试性能 long t1 = System.currentTimeMillis(); test(DemoTest::forSum, 1000000); System.out.println("forSum: " + " -> " + (System.currentTimeMillis() - t1) + " ms"); t1 = System.currentTimeMillis(); test(DemoTest::streamSum, 1000000); System.out.println("streamSum: " + " -> " + (System.currentTimeMillis() - t1) + " ms"); t1 = System.currentTimeMillis(); test(DemoTest::paralleSum, 1000000); System.out.println("paralleSum: " + " -> " + (System.currentTimeMillis() - t1) + " ms"); t1 = System.currentTimeMillis(); test(DemoTest::rangedSum, 1000000); System.out.println("rangedSum: " + " -> " + (System.currentTimeMillis() - t1) + " ms"); t1 = System.currentTimeMillis(); test(DemoTest::paralleRangedSum, 1000000); System.out.println("paralleRangedSum: " + " -> " + (System.currentTimeMillis() - t1) + " ms"); } // stream求和 public static long streamSum(long n) { return Stream.iterate(1L, i -> i+1) .limit(n) .reduce(0L, Long::sum); } // for求和 public static long forSum(long n) { long result = 0; for (int i = 0; i <= n; i++) { result += i; } return result; } //paralle求和 public static long paralleSum(long n) { return Stream.iterate(1L, i -> i+1) .limit(n) .parallel()// 将流转换为并行流 .reduce(0L, Long::sum); } // 测试性能--运行10次 public static void test(Function<Long, Long> function, long n) { long result = 0; for (int i = 0; i < 10; i++) { result = function.apply(n); } System.out.println(result); } // 优化 public static long rangedSum(long n) { return LongStream.rangeClosed(0L, n) .reduce(0L, Long::sum); } public static long paralleRangedSum(long n) { return LongStream.rangeClosed(0L, n) .parallel() .reduce(0L, Long::sum); } }
总结:
| 源 | 可分解性 |
| ArrayList | 极佳 |
| LinkedList | 差 |
| IntStream.range | 极佳 |
| Stream.iterate | 差 |
| HashSet | 好 |
| TreeSet | 好 |
备注:
摘自文献:《Java8实战》(中文版)《Java8 in Action》(英文版)
代码(GitHub地址): https://github.com/changlezhong/java8InAction
posted on 2018-06-10 20:26 changlezhong 阅读(210) 评论(0) 收藏 举报
浙公网安备 33010602011771号