Java8 Stream 对集合进行操作的性能是否比传统方式快?

Java8 Stream 对集合进行操作的性能是否比传统方式快?

以下代码中 s1()s2()两个方法的执行所用时间平均相差6秒左右,为什么?如何分析?求教。
【若将s1()中的串行流改成并行流则更慢。。欢迎评论[]( ̄▽ ̄)*】

import java.util.*;
import java.util.stream.Stream;

public class TestStream {

    public static void main(String[] args) {

        long tn = 100000000;
        long s0 = 0;
        long s1 = 0;

        long start = System.currentTimeMillis();
        for (long i = 1; i <= tn; i++) {
            s1();
            if (i % 10000 == 0) {
                s0 = System.currentTimeMillis() - start;
                System.out.println(i + " time: " + s0);
            }
        }

        long start1 = System.currentTimeMillis();
        for (long i = 1; i <= tn; i++) {
            s2();
            if (i % 10000 == 0) {
                s1 = System.currentTimeMillis() - start1;
                System.out.println(i + " time: " + s1);
            }
        }

        System.out.println(">>>>>>>> " + (s0 - s1));

    }

    private static Optional<String> s1() {
        return Stream.of("a", "b", "c", "d", "e").sorted(Comparator.reverseOrder()).reduce(String::concat);
    }

    private static String s2() {
        List<String> stringList = new ArrayList<>();
        stringList.add("a");
        stringList.add("b");
        stringList.add("c");
        stringList.add("d");
        stringList.add("e");
        Collections.reverse(stringList);
        String out = "";
        for (String string : stringList) {
            out = out.concat(string);
        }
        return out;
    }

}

你可能感兴趣的:(Java,讨论)