Stream
中有一些方法,特别是在处理可以这样或那样写的数值时。 (同样的问题适用于 average()
)
那么哪种方法更可取:
DoubleSummaryStatistics result;
result = stream()
.collect( Collectors.summarizingDouble( weighter::weight ) );
对比
result = stream()
.mapToDouble( weighter::weight )
.summaryStatistics();
为什么?
(如我所见,第一个的优点是每个元素只“访问”一次,而第二个具有更清晰的语义,但至少访问每个元素两次。但这是否重要/正确?)
最佳答案
在性能方面,似乎第二种方法(映射然后总结)比第一种方法(使用收集器)更快:
Benchmark (n) Mode Samples Score Error Units
c.a.p.SO26775395.collector 10 avgt 10 0.110 ± 0.004 us/op
c.a.p.SO26775395.collector 1000 avgt 10 9.134 ± 0.310 us/op
c.a.p.SO26775395.collector 1000000 avgt 10 9091.649 ± 274.113 us/op
c.a.p.SO26775395.summary 10 avgt 10 0.110 ± 0.003 us/op
c.a.p.SO26775395.summary 1000 avgt 10 5.593 ± 0.234 us/op
c.a.p.SO26775395.summary 1000000 avgt 10 5598.776 ± 153.314 us/op
基准代码:
@State(Scope.Thread)
@BenchmarkMode(Mode.AverageTime)
public class SO26775395 {
@Param({"10", "1000", "1000000"}) int n;
List<Weighter> weights;
@Setup public void setup() {
weights = new Random().doubles(n)
.mapToObj(Weighter::new)
.collect(toList());
}
@Benchmark public DoubleSummaryStatistics collector() {
return weights.stream().collect(Collectors.summarizingDouble(Weighter::w));
}
@Benchmark public DoubleSummaryStatistics summary() {
return weights.stream().mapToDouble(Weighter::w).summaryStatistics();
}
public static class Weighter {
private final double w;
public Weighter(double w) { this.w = w; }
public double w() { return w; }
}
}
关于java - 流收集与 map 收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26775395/