且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java流惰性vs融合vs短路

更新时间:2023-12-04 17:36:16

至于融合.让我们想象一下这是一个 map 操作:

As for fusion. Let's imagine here's a map operation:

.map(x -> x.squash())

它是无状态的,它只是根据指定的算法转换任何输入(在我们的例子中是压缩它们).现在进行过滤操作:

It's stateless and it just transforms any input according to the specified algorithm (in our case squashes them). Now the filter operation:

.filter(x -> x.getColor() != YELLOW)

它也是无状态的,它只是删除了一些元素(在我们的例子中是黄色的).现在让我们进行终端操作:

It's also stateless and it just removes some elements (in our case yellow ones). Now let's have a terminal operation:

.forEach(System.out::println)

它只是向终端显示输入元素.融合意味着所有中间无状态操作都与终端消费者合并为单个操作:

It just displays the input elements to the terminal. The fusion means that all intermediate stateless operations are merged with terminal consumer into single operation:

.map(x -> x.squash())
.filter(x -> x.getColor() != YELLOW)
.forEach(System.out::println)

整个管道被融合成一个Consumer,它直接连接到源.当处理每个元素时,源拆分器只执行组合消费者,流管道不拦截任何内容,也不执行任何额外的簿记.那是融合.融合不依赖于短路.可以在没有融合的情况下实现流(执行一个操作,获取结果,执行下一个操作,在每个操作后将控制权返回给流引擎).也可以在不短路的情况下进行融合.

The whole pipeline is fused into single Consumer which is connected directly to the source. When every single element is processed, the source spliterator just executes the combined consumer, the stream pipeline does not intercept anything and does not perform any additional bookkeeping. That's fusion. Fusion does not depend on short-circuiting. It's possible to implement streams without fusion (execute one operation, take the result, execute the next operation, taking the control after each operation back to the stream engine). It's also possible to have fusion without short-circuiting.