java Stream 和 parallelStream比较

java 8 有一个新的特性就是流,其中stream和parallelStream就是一种流的处理方式,前者是单管,后者是多管道,在性能上做一个对比看看两者的差别。

首先写一个方法,用来生成一个大小为60000的list:

 public static List<Integer> buildIntRange() {
    List<Integer> numbers = new ArrayList<>(5);
    for (int i = 0; i < 60000; i++)
      numbers.add(i);
    return Collections.unmodifiableList(numbers);
  }

用传统的for循环和stream以及parallelStream对上面产生的list进行遍历,用两种不同的方式进行处理:

一:每次sleep 1毫秒,用来模拟每次循环耗时
public static void main(String[] args) {
    List<Integer> source = buildIntRange();

    // 传统方式的遍历
    long start = System.currentTimeMillis();
    for (int i = 0; i < source.size(); i++) {
      try {
        TimeUnit.MILLISECONDS.sleep(1);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }
    System.out.println("传统方式 : " + (System.currentTimeMillis() - start) + "ms");

    // 单管道stream
    start = System.currentTimeMillis();
    source.stream().forEach(r -> {
      try {
        TimeUnit.MILLISECONDS.sleep(1);
      } catch (Exception e) {
        e.printStackTrace();
      }
    });
    System.out.println("stream : " + (System.currentTimeMillis() - start) + "ms");

    // 多管道parallelStream
    start = System.currentTimeMillis();
    source.parallelStream().forEach(r -> {
      try {
        TimeUnit.MILLISECONDS.sleep(1);
      } catch (Exception e) {
        e.printStackTrace();
      }
    });
    System.out.println("parallelStream : " + (System.currentTimeMillis() - start) + "ms");

  }

运行结果: 


二:直接将每次循环得到的值写入text文件
写入文件的方法:

public static void write(String source,String path) {
    BufferedWriter output = null;
    try {
      File file = new File(path);
      output = new BufferedWriter(new FileWriter(file,true)); //true表示是否追加
      output.write(source);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (output != null) try {
        output.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
  }

处理list的方法:

 public static void main(String[] args) {
    List<Integer> source = buildIntRange();

    // 传统方式的遍历
    long start = System.currentTimeMillis();
    for (int i = 0; i < source.size(); i++) {
      write(source.get(i)+";", "D://example1.txt");
    }
    System.out.println("传统方式 : " + (System.currentTimeMillis() - start) + "ms");

    // 单管道stream
    start = System.currentTimeMillis();
    source.stream().forEach(r -> {
      write(r+";", "D://example2.txt");
    });
    System.out.println("stream : " + (System.currentTimeMillis() - start) + "ms");

    // 多管道parallelStream
    start = System.currentTimeMillis();
    source.parallelStream().forEach(r -> {
      write(r+";", "D://example3.txt");
    });
    System.out.println("parallelStream : " + (System.currentTimeMillis() - start) + "ms");

  }

运行结果如下: 


由此可见,传统方式跟单管道stream的处理效率相差无几,多管道parallelStream的处理效率最高。
 

猜你喜欢

转载自blog.csdn.net/xiaoliuliu2050/article/details/85999008