How does Java 8 maptoint (maptoint (E – > e)) improve performance?

I'm reading the book "Java 8 Lambdas". At some time, the author said, "it's a good idea to use the original professional functions as much as possible, because

Here he refers to maptoint, maptolong, etc

In fact, I didn't know that actors' performance came from honesty

Let's take 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);

Therefore, in the first case, I use reduce to calculate the value, so the binaryoperator function will always receive int (ACC) and integer (the current element of the collection), and then unpack int (ACC) to integer

In the second case, I use maptoint, which unpacks each integer into an int and sums it

My question is, what are the benefits of the second method? What other maps to int when I can use maps?

So yes, is this just sugar syntax, or does it have some performance advantages? If yes, please provide some information

to greet,

Solution

There are more boxing levels

int sum1 = list.stream().reduce(0,e) -> acc + e).intValue();

Because the restore function is a binary operator < integer > – it takes two integer values, cancels the inbox, adds them, and repackages the result The maptoint version unpacks the integer element from the list once, and then uses the original int value as intstream

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>