Sequence in filter - does it matter?

Viewed 66

Lets consider that we have following boolean condition:
A,B,C,D.
Now we would like to filter list according to them:
list.stream().filter(x -> A).filter(x -> B).filter(x -> C).filter(x -> D)

list.stream().filter(x -> A && B && C && D)

What way is better ? I mean efficiency and elegance.

2 Answers

In terms of raw efficiency, the combined filter will be slightly better. But the cases where that actually makes a difference for your application should be very rare. I'd treat it as premature optimization.

And the cost of introducing such optimizations is tightly-coupled, error-prone code that does to many things at once and can't easily be tested.

If you follow the Single Responsibility Principle strictly, then one filter should only apply one criterion. It makes your code more obvious and readable, even though it may cost you some nanoseconds.

In terms of efficiency, there is a slight drawback with the first example; there will be more objects created when chaining multiple intermediate filter operations together, the reason being that each filter intermediate operation returns a new stream. whereas with the other approach you don't have that slight overhead.

What way is better ? I mean efficiency and elegance.

you should go with whichever of the two you want as the performance difference is minimal.

Related