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

五迷三道 提交于 2019-12-03 11:19:22

问题


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:


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.



来源:https://stackoverflow.com/questions/25269346/how-does-java-8-maptoint-maptointe-e-improves-performance-exactly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!