Kay*_*ayV 2 java collect java-8 java-stream collectors
我最近开始使用collectAndThen,发现与其他编码程序相比,它需要花费相当长的时间,我用它来执行类似的任务.
这是我的代码:
System.out.println("CollectingAndThen");
Long t = System.currentTimeMillis();
String personWithMaxAge = persons.stream()
.collect(Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparing(Person::getAge)),
(Optional<Person> p) -> p.isPresent() ? p.get().getName() : "none"
));
System.out.println("personWithMaxAge - "+personWithMaxAge + " time taken = "+(System.currentTimeMillis() - t));
Long t2 = System.currentTimeMillis();
String personWithMaxAge2 = persons.stream().sorted(Comparator.comparing(Person::getAge).reversed())
.findFirst().get().name;
System.out.println("personWithMaxAge2 : "+personWithMaxAge2+ " time taken = "+(System.currentTimeMillis() - t2));
Run Code Online (Sandbox Code Playgroud)
在这里输出:
CollectingAndThen
personWithMaxAge - Peter time taken = 17
personWithMaxAge2 : Peter time taken = 1
Run Code Online (Sandbox Code Playgroud)
这表明收集和收集时间相对较长.
所以我的问题是 - 我应该继续收集和其他建议吗?
Hol*_*ger 11
collectingAndThen 添加一个仅在集合末尾执行的操作.
所以
String personWithMaxAge = persons.stream()
.collect(Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparing(Person::getAge)),
(Optional<Person> p) -> p.isPresent() ? p.get().getName() : "none"
));
Run Code Online (Sandbox Code Playgroud)
并没有什么不同
Optional<Person> p = persons.stream()
.collect(Collectors.maxBy(Comparator.comparing(Person::getAge)));
String personWithMaxAge = p.isPresent() ? p.get().getName() : "none";
Run Code Online (Sandbox Code Playgroud)
在收集器中指定操作的实际优点显示当您使用生成的收集器作为另一个收集器的输入时,例如groupingBy(f1, collectingAndThen(collector, f2)).
由于这是在结束时执行一次的单个微不足道的动作,因此对性能没有影响.此外,sorted基于maxBy任何非平凡输入的操作,基于解决方案的速度不太可能.
您只是使用破坏的基准测试违反了" 如何在Java中编写正确的微基准测试 "中列出的几条规则?".最值得注意的是,您正在测量Stream框架第一次使用的初始初始化开销.只是交换两个操作的顺序将给你一个完全不同的结果.
但是,不需要使操作不必要地复杂化.如上所述,镜像现有Stream操作的收集器的优点是它们可以与其他收集器组合.如果不需要这样的组合,只需使用直接的代码
String personWithMaxAge = persons.stream()
.max(Comparator.comparing(Person::getAge))
.map(Person::getName).orElse("none");
Run Code Online (Sandbox Code Playgroud)
这比收集器使用更简单,并且比sorted基于解决方案更有效.
TL; DR; 你测量事物的方式可能是关闭的.
我使用JMH创建了一个更有效的测试性能平台,设置如下(人员列表应该以不同方式初始化,以进一步增强对结果的信心):
public static void main(String[] args) throws RunnerException {
Options opt = new OptionsBuilder().include(SO.class.getSimpleName()).jvmArgs("-Dfile.encoding=UTF-8").build();
new Runner(opt).run();
}
public static final class Person {
public Person(String name, int age) {
this.name = name;
this.age = age;
}
String name;
int age;
public int getAge() {return age;};
public String getName() {return this.name;}
}
public static final List<Person> persons = IntStream.range(0, 100).mapToObj(i -> new Person("person" + i, RandomUtils.nextInt(0, 50))).collect(Collectors.toList());
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@Warmup(iterations = 5, time = 4, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 4, time = 5, timeUnit = TimeUnit.SECONDS)
@Fork(2)
public float collectingAndThen() {
String personWithMaxAge = persons.stream()
.collect(Collectors.collectingAndThen(
Collectors.maxBy(Comparator.comparing(Person::getAge)),
(Optional<Person> p) -> p.isPresent() ? p.get().getName() : "none"
));
return personWithMaxAge.length() * 1.0f;
}
@Benchmark
@BenchmarkMode(Mode.Throughput)
@OutputTimeUnit(TimeUnit.SECONDS)
@Warmup(iterations = 5, time = 4, timeUnit = TimeUnit.SECONDS)
@Measurement(iterations = 4, time = 5, timeUnit = TimeUnit.SECONDS)
@Fork(2)
public float sortFindFirst() {
String personWithMaxAge2 = persons.stream().sorted(Comparator.comparing(Person::getAge).reversed())
.findFirst().get().name;
return personWithMaxAge2.length() * 1.0f;
}
Run Code Online (Sandbox Code Playgroud)
结果在这个测试中是毋庸置疑的(列表中有100人):
# Run complete. Total time: 00:02:41
Benchmark Mode Cnt Score Error Units
Benchmark.SO.collectingAndThen thrpt 8 1412304,072 ± 53963,266 ops/s
Benchmark.SO.sortFindFirst thrpt 8 331214,270 ± 7966,082 ops/s
Run Code Online (Sandbox Code Playgroud)
收集和收集时间要快4倍.
如果您将人员名单缩小到5人,则数字会完全改变:
Benchmark Mode Cnt Score Error Units
Benchmark.SO.collectingAndThen thrpt 8 14529905,529 ± 423196,066 ops/s
Benchmark.SO.sortFindFirst thrpt 8 7645716,643 ± 538730,614 ops/s
Run Code Online (Sandbox Code Playgroud)
但是收集和然后仍然快2倍.
我怀疑你的测试是关闭的.有许多可能的原因,例如,类加载,JIT编译和其他热身,......
正如@assylias在评论中指出的那样,你应该依靠更精心设计的微基准来测量这种"小"方法的时间,以避免之前提到的副作用.请参阅:如何在Java中编写正确的微基准测试?
不,collectingAndThen从效率的角度来看是好的.
考虑此代码生成随机整数列表:
List<Integer> list =
new Random().ints(5).boxed().collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
您可以使用以下两种方法从此列表中获取最大值:
list.stream().collect(Collectors.collectingAndThen(
Collectors.maxBy(Comparator.naturalOrder()),
(Optional<Integer> n) -> n.orElse(0)));
Run Code Online (Sandbox Code Playgroud)
和
list.stream().sorted().findFirst().get();
Run Code Online (Sandbox Code Playgroud)
如果您只是单次执行这两种方法,您可能会得到类似这样的时间(ideone):
collectAndThen 2.884806
sortFindFirst 1.898522
Run Code Online (Sandbox Code Playgroud)
那些是以毫秒为单位的时间.
但是继续迭代,你会发现时间变化很大.经过100次迭代:
collectAndThen 0.00792
sortFindFirst 0.010873
Run Code Online (Sandbox Code Playgroud)
仍然以毫秒为单位.
因此,如前所述,您只是没有正确地对这两种方法进行基准测试.
| 归档时间: |
|
| 查看次数: |
1894 次 |
| 最近记录: |