我想过滤 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/