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

本文通过一个具体的案例对比了Java中使用并行流和平行流进行数据处理的性能差异,并探讨了导致性能变化的原因,提供了改进方案。

直接上代码:

              //组装实体类
		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                     好

转载于:https://www.cnblogs.com/sg9527/p/7911994.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值