java - RxJava - Observable - 多个过滤器调用与一个过滤器调用

标签 java rx-java rx-java2

我想过滤 Observable 发出的项目,但我有很多过滤条件,我想知道什么是更好的方法 - 性能明智。

一种方法是调用一个“filter”方法,该方法具有多个“if”语句中的所有条件并返回最终过滤结果,并调用:

observable
    .filter(this::filter)

另一种方法是拥有多个“filterX”方法,每个方法都按特定条件进行过滤,并在链中调用它们:

observable
    .filter(this::filterX)
    .filter(this::filterY)
    .filter(this::filterZ)

我的问题是 - 是否存在任何性能差异,两者中哪一个是“更好的做法”? 我发现第二个更好,更易读,但目前我遇到了一个带有 ~30 个“if”语句的“过滤器”方法,我想知道我是否应该打扰并将其重构为第二种方法。

最佳答案

RxJava库试图用Operator Fusion的概念来优化你描述的场景:

Operator fusion has the premise that certain operators can be combined into one single operator (macro-fusion) or their internal data structures shared between each other (micro-fusion) that allows fewer allocations, lower overhead and better performance.

它在 design document 中给出了有关过滤器运算符的具体示例:

  • a is b and the two operator's parameter set can be combined into a single application. Example: filter(p1).filter(p2) combined into filter(p1 && p2).

因此,在您的情况下,库将尽力组合所有过滤器,以免性能差异太大。

关于java - RxJava - Observable - 多个过滤器调用与一个过滤器调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56293517/

相关文章:

java - 将 pcm 样本链接在一起时避免静态和失真

java - 没有 EJB 就不能做什么

java - RxJava : Calling . subscribe() 使用相同的观察者来处理多个 Observables

android - 如何管理 RxJava 中需要的 Looper 线程

java - 在 RxJava 2 的 Observable 中发出字符串数组时出现“不兼容类型”错误

java - 使用您的 GMail 收件箱空间?

java - 优化小型 int 数组上的方法,java

kotlin - 哪个RxJava运算符使其更简单

android - 在 retrofit2 界面中检索 SharedPreferences

rx-java - 为什么在 replay() 之前调用publish()很重要