gpt4 book ai didi

java - 为什么无序流比有序流快?

转载 作者:搜寻专家 更新时间:2023-11-01 02:04:42 25 4
gpt4 key购买 nike

我正在阅读 Richard Warburton 的 Java 8 书并想到了这个:

Some operation are more expensive on ordered stream. This problem can be solved by eliminating ordering. To do so, call the stream's unordered method. [...]

我对此感到很困惑。假设我们有 Stream<Integer> stream = Arrays.asList(1, 2, 3, 4).stream();

List<Integer>为流(一些)操作定义一个相遇顺序可能执行效率低下。这是为什么?

它如何影响处理,是什么让它变慢?为了加快速度,在那种情况下,我们应该将其称为

Stream<Integer> stream = Arrays.asList(1, 2, 3, 4).stream().unordered();

?听起来很奇怪,至少可以说...

最佳答案

这在文档中有详细解释: https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

Ordering
Streams may or may not have a defined encounter order. Whether or not a stream has an encounter order depends on the source and the intermediate operations. Certain stream sources (such as List or arrays) are intrinsically ordered, whereas others (such as HashSet) are not. Some intermediate operations, such as sorted(), may impose an encounter order on an otherwise unordered stream, and others may render an ordered stream unordered, such as BaseStream.unordered(). Further, some terminal operations may ignore encounter order, such as forEach().

If a stream is ordered, most operations are constrained to operate on the elements in their encounter order; if the source of a stream is a List containing [1, 2, 3], then the result of executing map(x -> x*2) must be [2, 4, 6]. However, if the source has no defined encounter order, then any permutation of the values [2, 4, 6] would be a valid result. For sequential streams, the presence or absence of an encounter order does not affect performance, only determinism. If a stream is ordered, repeated execution of identical stream pipelines on an identical source will produce an identical result; if it is not ordered, repeated execution might produce different results.

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/37225639/

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