iterate使用了parallel() 反而消耗了更多的时间

直接上代码:

              //组装实体类
		Trader raoul = new Trader("Raoul", "Cambridge");
		List<Transaction> transactions = new ArrayList<Transaction>();
		for (int j = 0; j < 100000; j++) {
			Transaction t = new Transaction(raoul,2100,j);
			transactions.add(t);
		}
		//开始对比
		long l1 = System.currentTimeMillis();
		int i = transactions.stream()
		.parallel()
		.collect(Collectors.summingInt(Transaction::getValue));
		System.out.println("使用了并行:计算结果:"+i +",所用时间  "+(System.currentTimeMillis()-l1));
		
		long l2 = System.currentTimeMillis();
		int dd = transactions.stream()
		.collect(Collectors.summingInt(Transaction::getValue));
		System.out.println("未使用了并行:计算结果:"+dd +",所用时间  "+(System.currentTimeMillis()-l2));                

 结果:

使用了并行:计算结果:704982704,所用时间  127
未使用了并行:计算结果:704982704,所用时间  13

 使用了parallel() 反而消耗了更多的时间

原因:

 iterate生成的是装箱的对象,必须拆箱成数字才能求和;
 我们很难把iterate分成多个独立块来并行执行。

可以利用的解决方法:

留意装箱。自动装箱和拆箱操作会大大降低性能。Java 8中有原始类型流(IntStream、LongStream、DoubleStream)来避免这种操作,但凡有可能都应该用这些流。

 LongStream.rangeClosed会生成数字范围,很容易拆分为独立的小块。例如,范围1~20可分为1~5、6~10、11~15和16~20。

 

                          流的数据源和可分解性
源                     可分解性
ArrayList                   极佳
LinkedList                   差
IntStream.range                极佳
Stream.iterate                  差
HashSet                      好
TreeSet                     好

posted on 2017-11-28 20:51  一个帅哥9527  阅读(283)  评论(0编辑  收藏  举报