Java Streams .max()和.min()在性能上滞后吗? [英] Java Streams .max() and .min() lag in performance?

查看:62
本文介绍了Java Streams .max()和.min()在性能上滞后吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下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.max() 不需要自定义比较器.

Try mapping to an IntStream. An IntStream works with ints internally, which avoids the overhead of boxing and unboxing Integer objects. Also, IntStream.max() doesn't need a custom comparator.

因此,您认为最主要的原因是装箱"和取消装箱"?

So you suggest that the prominent reason is 'boxing' and 'unboxing'?

如果没有通过基准测试运行它,我不知道它是否会符合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()在性能上滞后吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆