问题描述
考虑以下2个示例.
myList.stream().map(this::getInt).max(Integer::compareTo);
2旧方式
int max = Integer.MIN_VALUE;
for (MyItem item : myList) {
max = Math.max(max, getInt(item));
}
getInt
以上的方法接受MyItem
自变量并返回int
结果.
Above getInt
method accepts a MyItem
argument and returns an int
result.
在这里,与#1相比,#2给我的等待时间要短得多.有谁知道为什么或者我有什么问题吗?
Here, #2 gives me a much lower latency compared to #1. Does anyone have an idea why or anything going wrong for me?
推荐答案
myList.stream().mapToInt(this::getInt).max()
尝试映射到IntStream
. IntStream
在内部与int
一起使用,这避免了对Integer
对象进行装箱和拆箱的开销.另外, IntStream.max()
不需要自定义比较器.
Try mapping to an IntStream
. An IntStream
works with int
s internally, which avoids the overhead of boxing and unboxing Integer
objects. Also, IntStream.max()
doesn't need a custom comparator.
如果没有通过基准测试运行它,我不知道它是否会符合for
循环的性能.但这将是一个进步.如果还不够好,那么我建议您坚持使用循环,因为我看不到任何其他改进方法.
Without running it through your benchmark I don't know if it'll match the for
loop's performance. But it'll be an improvement. If it's not good enough then I suggest sticking with the loop as I don't see any other way to improve it.
这篇关于Java Streams .max()和.min()在性能上滞后吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!