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

RxJava - Observable - multiple filter calls vs one filter call

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

一种方法是调用 one "filter" 方法,该方法具有多个 "if" 语句中的所有条件和 returns 最后一个过滤结果,调用:

observable
    .filter(this::filter)

另一种方法是使用多个 "filterX" 方法,每个方法都按特定条件进行过滤,然后在链中调用它们:

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

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

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).

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