RxJava - Observable - multiple filter calls vs one filter call

sas :

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.

Gustavo :

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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=92824&siteId=1