Skip to content
Advertisement

Does the order of applying comparators and predicates matter?

We have a web page, where the user can select an arbitrary number of rules for filtering and sorting a group of items. With each rule, he sets a priority for it, with which the user defines the order of how the rules should be applied.

From this group of rules I extract Comparator (if the rule was sorting) and/or Predicates (if the user wants to filter the items) objects. I would like to use these with a stream of items, in order to filter and sort them.

My question is, does the order of applying the Comparator and Predicate objects matter? I know that the order of Comparator objects is important, but does it matter if a Predicate appears at the start or at the end?

For example:

We have Comparator objects: comparator1, comparator2
We have Predicate objects: predicate1, predicate2

Is there a difference between applying them in the following orders:

- comparator1, comparator2, predicate1, predicate2
- predicate1, predicate2, comparator1, comparator2
- predicate1, comparator1, predicate2, comparator2
- predicate2, comparator1, comparator2, predicate1

Note: comparator1 always appears before comparator2. I am aware that changing their order could result in different results in terms of sorting.

Now, I think that all the above situations would result in the same output (in terms of sorting and items). This would allow me to apply all filters first and then take care of sorting. But I am not sure, so I had to ask here.

Advertisement

Answer

If your predicates are stateless and do not modify the objects they test, then they are selections in terms of relational algebra. As such, their ordering does not matter for the end result.

However, there might be differences in performance. It is generally advisable to apply fast and highly selective predicates first. Sorting will also be faster after filtering.

On the other hand, depending on what you are doing these benefits might be negligible. In such cases you should go for the order that makes you code the easiest to understand and maintain.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement