简体   繁体   中英

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.

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:

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:

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.

RxJava library tries to optimize the scenario described by you with the concept of 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. Example: filter(p1).filter(p2) combined into filter(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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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