Is there any advantage of calling map after mapToInt, where ever required

前端 未结 3 797
误落风尘
误落风尘 2020-12-31 09:57

I am trying to calculate the sum of squares of values in the list. Below are three variations which all calculates the required value. I want to know which one is the most e

3条回答
  •  北荒
    北荒 (楼主)
    2020-12-31 10:11

    I expect the second one to be the fastest.

    There is boxing in neither the second nor the third example (if the list contains already boxed elements). But, there is unboxing.

    Your second example might have two unboxing (one for every x in x*x), while the third does unboxing only once. However, unboxing is fast and I think it does not worth to optimize that as a longer pipeline with an additional function call will certainly slow it down.

    Sidenote: in general, you should not expect Streams to be faster than regular iterations on arrays or lists. When doing mathematical calculations where speed matters (like this) it's better to go the other way: simply iterate through the elements. If your output is an aggregated value, then aggregate it, if it is a mapping, then allocate a new array or list of the same size and fill it with the calculated values.

提交回复
热议问题