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,
1)mapToInt function's main purpose is to convert current stream to Intstream, over which other Integer operations can be performed like sum,Min,max etc. It's generics you can never predict what will be the input, in your case it is String, it might be double ,long or Something else.
Introduced in Java 8, the Stream API is used to process collections of objects. A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result.
So how does it work internally? It's actually pretty simple. Java uses trySplit method to try splitting the collection in chunks that could be processed by different threads. In terms of the execution plan, it works very similarly, with one main difference.
Java streams enable functional-style operations on streams of elements. A stream is an abstraction of a non-mutable collection of functions applied in some order to the data. A stream is not a collection where you can store elements.
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 once and then works with primitive int
values from that point on as an IntStream
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With