gpt4 book ai didi

java - 这会产生更快的并行流吗?

转载 作者:行者123 更新时间:2023-12-01 20:23:36 27 4
gpt4 key购买 nike

OCP 书中说,默认情况下所有流都是有序的,但可以使用 unordered() 方法将有序流转换为无序流。

还说,当我在调用parallel()终端操作之前使用该方法作为中间操作时,该方法可以极大地提高性能。我的问题是:下面的并行流会比下面的并行流更快吗?

Arrays.asList(1,2,3,4,5,6).stream().unordered().parallel()

Arrays.asList(1,2,3,4,5,6).parallelStream().

PS:我知道并行流在处理小型集合时不会提高性能,但让我们假装我们正在处理非常大的集合。

第二个流仍然是有序的,对吗?那么第一个会有更好的性能吗?

谢谢

最佳答案

您声明所有流都是默认排序的:事实并非如此。例如,如果您的源是 HashSet,则生成的流将不会排序。

关于使并行流无序以“极大地提高性能”的问题:一如既往,当谈到性能时,它取决于(取决于终端操作、中间操作、流的大小等)

The java.util.stream package javadoc给出了一些至少部分回答您的问题的提示:

For parallel streams, relaxing the ordering constraint can sometimes enable more efficient execution. Certain aggregate operations, such as filtering duplicates (distinct()) or grouped reductions (Collectors.groupingBy()) can be implemented more efficiently if ordering of elements is not relevant. Similarly, operations that are intrinsically tied to encounter order, such as limit(), may require buffering to ensure proper ordering, undermining the benefit of parallelism. In cases where the stream has an encounter order, but the user does not particularly care about that encounter order, explicitly de-ordering the stream with unordered() may improve parallel performance for some stateful or terminal operations. However, most stream pipelines, such as the "sum of weight of blocks" example above, still parallelize efficiently even under ordering constraints.

关于java - 这会产生更快的并行流吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44238453/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com