![](/img/trans.png)
[英].collect(Collectors.toList()) and Streams on Java Method
[英]Java .forEach(list::add) vs .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());
我已經針對大小為100萬的列表測試了這兩種方案。 總體而言,順序流幾乎沒有區別,但並行流卻有區別:
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
列出列表,因為它違反了函數純度規則,並且在與並行流一起使用時收集效率更高。
@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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.