Java 8 mapToInt ( mapToInt(e -> e) ) 如何准确提高性能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25269346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does Java 8 mapToInt ( mapToInt(e -> e) )improves performance exactly?
提问by adragomir
I'm reading the book "Java 8 Lambdas", and at some point the author says "It's a good idea to use the primitive specialized functions wherever possible because of the performance benefits.".
我正在阅读“Java 8 Lambdas”一书,在某些时候作者说“由于性能优势,尽可能使用原始的专用函数是个好主意。”。
He is referring here to mapToInt, mapToLong, etc.
他在这里指的是 mapToInt、mapToLong 等。
The thing is I don't know where the performance comes from to be honest.
问题是老实说我不知道性能来自哪里。
Let's consider an example:
让我们考虑一个例子:
// Consider this a very very long list, with a lot of elements
List<Integer> list = Arrays.asList(1, 2, 3, 4);
//sum it, flavour 1
int sum1 = list.stream().reduce(0, (acc, e) -> acc + e).intValue();
//sum it, flavour 2
int sum2 = list.stream().mapToInt(e -> e).sum();
System.out.println(sum1 + " " + sum2);
So, in the first case I use reduce to sum the values, so the BinaryOperator function will receive all the time an int ( acc ) and an Integer ( the current element of the collection ) and then will do an unboxing of the Integer to the int ( acc + e)
因此,在第一种情况下,我使用 reduce 对值求和,因此 BinaryOperator 函数将始终接收一个 int ( acc ) 和一个 Integer ( 集合的当前元素),然后将 Integer 拆箱到int (acc + e)
In the second case, I use mapToInt, which unboxes each Integer into an int, and then sums it.
在第二种情况下,我使用 mapToInt,它将每个 Integer 拆箱为一个 int,然后对它求和。
My question is, is there any advantage of the second approach? Also what's the point of map to int, when I could have used map?
我的问题是,第二种方法有什么好处吗?另外,当我可以使用 map 时,map to int 的意义何在?
So yeah, is it all just sugar syntax or does it has some performance benefits? In case it does, please offer some information
所以是的,这只是糖语法还是它有一些性能优势?如果有,请提供一些信息
Regards,
问候,
回答by Ian Roberts
There's an extra level of boxing going on in
有一个额外的拳击水平在进行中
int sum1 = list.stream().reduce(0, (acc, e) -> acc + e).intValue();
as the reduction function is a BinaryOperator<Integer>
- it gets passed two Integer
values, unboxes them, adds them, and then re-boxes the result. The mapToInt
version unboxes the Integer
elements from the list onceand then works with primitive int
values from that point on as an IntStream
.
因为reduce函数是a BinaryOperator<Integer>
- 它传递了两个Integer
值,将它们拆箱,添加它们,然后重新装箱结果。该mapToInt
版本Integer
将列表中的元素拆箱一次,然后从那时起将原始int
值作为IntStream
.