zoukankan      html  css  js  c++  java
  • 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                     好

  • 相关阅读:
    HDU 4814
    POJ 3415
    HDU 4941
    C scanf()
    hdu 4850 Wow! Such String!
    HDU 4828 Grids
    HDU 4832 Chess
    HDU 4831
    SpringCloud 网飞系 转换阿里系2
    用jianmu建木自动化打包vue前端应用,并远程ssh建立文件夹,scp文件至对应目录
  • 原文地址:https://www.cnblogs.com/sg9527/p/7911994.html
Copyright © 2011-2022 走看看