简体   繁体   English

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

[英]RxJava - Observable - multiple filter calls vs one filter call

I want to filter items emitted by an Observable, but I have many filter criterias and I'm wondering what is the better way to do that - performance wise. 我想过滤一个Observable发出的项目,但是我有很多过滤器标准,我想知道更好的方法是什么 - 性能明智。

One way would be to call one "filter" method which has all of the criterias in multiple "if" statements and returns the final filtering result, and to call: 一种方法是调用一个 “过滤器”方法,该方法在多个“if”语句中包含所有标准并返回最终过滤结果,并调用:

observable
    .filter(this::filter)

Another way would be to have multiple "filterX" methods, each filters by a specific criteria, and call them in a chain: 另一种方法是使用多个“filterX”方法,每个方法按特定标准过滤,并在链中调用它们:

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

My question is - is there any performance difference and which of the two is 'better practice'? 我的问题是 - 是否有任何性能差异,两者中的哪一个是“更好的做法”? I find the second one nicer and more readable, but currently I encountered a "filter" method with ~30 'if' statements and I'm wondering if I should bother and refactor it to the second approach. 我发现第二个更好,更可读,但是目前我遇到了一个“过滤器”方法,有~30'if'语句,我想知道我是否应该打扰并重构它到第二种方法。

RxJava library tries to optimize the scenario described by you with the concept of Operator Fusion : 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. 运算符融合的前提是某些运算符可以组合成一个单独的运算符(宏融合)或它们彼此共享的内部数据结构(微融合),从而允许更少的分配,更低的开销和更好的性能。

It gives a specific example about the filter operator in the design document : 它给出了设计文档中过滤器运算符的具体示例:

  • a is b and the two operator's parameter set can be combined into a single application. a是b,两个运算符的参数集可以组合成一个应用程序。 Example: filter(p1).filter(p2) combined into filter(p1 && p2). 示例:过滤器(p1).filter(p2)组合成过滤器(p1 && p2)。

So, in your case, the library will try its best to combine all the filters in order to not have much performance difference. 因此,在您的情况下,库将尽力组合所有过滤器,以便没有太多的性能差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM