Java 8 mapToInt(mapToInt(e - > e))如何提高性能? [英] How does Java 8 mapToInt ( mapToInt(e -> e) )improves performance exactly?

查看:252
本文介绍了Java 8 mapToInt(mapToInt(e - > e))如何提高性能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读Java 8 Lambdas这本书,并且在某些时候作者说尽可能使用原始专用函数是个好主意,因为
的性能优势。。

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.".

他在这里指的是mapToInt,mapToLong等。

He is referring here to mapToInt, mapToLong, etc.

事情是我不知道性能来自哪里说实话。

The thing is I don't know where the performance comes from to be honest.

让我们考虑一个例子:

    // 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);

因此,在第一种情况下我使用reduce来对值求和,所以BinaryOperator函数将全部接收时间int(acc)和Integer(集合的当前元素)然后将整数拆箱到int(acc + e)

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)

在第二种情况下,我使用mapToInt,它将每个Integer解包成一个int,然后对它求和。

In the second case, I use mapToInt, which unboxes each Integer into an int, and then sums it.

我的问题是,第二种方法有什么优势吗?
当我可以使用map时,对于int的映射是什么意思?

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

因为减少函数是 BinaryOperator< Integer> - 它传递两个 Integer 值,将它们取消装箱,添加它们,然后重新打包结果。 mapToInt 版本从列表中取消 c>整数元素,然后使用原始 int 从该点开始的值为 IntStream

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.

这篇关于Java 8 mapToInt(mapToInt(e - &gt; e))如何提高性能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆