什么更快?
List<E> bar = new ArrayList<>();
pan.stream() /* other functions */.forEach(bar::add);
或者
List<E> bar = pan.stream() /* other functions */.collect(Collectors.toList());
什么更快?
List<E> bar = new ArrayList<>();
pan.stream() /* other functions */.forEach(bar::add);
或者
List<E> bar = pan.stream() /* other functions */.collect(Collectors.toList());
Benchmark Mode Cnt Score Error Units
Performance.collect avgt 200 0.022 ± 0.001 s/op
Performance.forEach avgt 200 0.021 ± 0.001 s/op
Performance.collectParallel avgt 200 0.124 ± 0.004 s/op
Performance.forEachParallel avgt 200 0.131 ± 0.001 s/op
我的看法是,你不应该使用forEach
来创建列表,因为它会违反函数纯度规则,而且在使用并行流时,使用collect更加高效。
@Benchmark @BenchmarkMode(Mode.AverageTime)
public void collect(Blackhole blackhole) {
Stream<Double> stream = Stream.iterate(0.0, e -> Math.random());
List<Double> list = stream.limit(1000000).collect(Collectors.toList());
blackhole.consume(list);
}
@Benchmark @BenchmarkMode(Mode.AverageTime)
public void forEach(Blackhole blackhole) {
Stream<Double> stream1 = Stream.iterate(0.0, e -> Math.random());
List<Double> list = new ArrayList<>();
stream1.limit(1000000).forEach(e -> list.add(e));
blackhole.consume(list);
}
@Benchmark @BenchmarkMode(Mode.AverageTime)
public void collectParallel(Blackhole blackhole) {
Stream<Double> stream = Stream.iterate(0.0, e -> Math.random());
List<Double> list = stream.parallel().limit(1000000).collect(Collectors.toList());
blackhole.consume(list);
}
@Benchmark @BenchmarkMode(Mode.AverageTime)
public void forEachParallel(Blackhole blackhole) {
Stream<Double> stream1 = Stream.iterate(0.0, e -> Math.random());
List<Double> list = Collections.synchronizedList(new ArrayList<>());
stream1.parallel().limit(1000000).forEach(e -> list.add(e));
blackhole.consume(list);
}
Collectors.toCollection
,并显式指定初始大小(以避免调整后备数组的大小)。 - Jacob G.