user3030447 user3030447 - 1 month ago 5x
Java Question

How does Java 8 mapToInt ( mapToInt(e -> e) )improves performance exactly?

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 =, (acc, e) -> acc + e).intValue();

//sum it, flavour 2
int sum2 = -> 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



There's an extra level of boxing going on in

int sum1 =, (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 once and then works with primitive int values from that point on as an IntStream.