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.".
He is referring here to mapToInt, mapToLong, etc.
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)
In the second case, I use mapToInt, which unboxes each Integer into an int, and then sums it.
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?
So yeah, is it all just sugar syntax or does it has some performance benefits? In case it does, please offer some information
Regards,
There's an extra level of boxing going on in
as the reduction function is a
BinaryOperator<Integer>
- it gets passed twoInteger
values, unboxes them, adds them, and then re-boxes the result. ThemapToInt
version unboxes theInteger
elements from the list once and then works with primitiveint
values from that point on as anIntStream
.