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

后端 未结 1 620
醉话见心
醉话见心 2021-02-05 05:06

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 perfor

相关标签:
1条回答
  • 2021-02-05 05:45

    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.

    0 讨论(0)
提交回复
热议问题