Paul
Paul

Reputation: 2047

Are logical operators in predicates short-circuited with NSFetchRequest?

I have an NSPredicate that uses the logical OR operator, like this:

NSPredicate(format: "activeFrom == NULL OR %@ >= activeFrom", someDate)

When I use this predicate to fetch results from CoreData, using NSFetchRequest, is the evaluation short-circuited so that the second clause isn't evaluated if the first clause evaluates to true?

It seems like a sensible optimisation for Apple to have implemented but I can't find anything official in the documentation to confirm it.

Upvotes: 2

Views: 118

Answers (1)

pbasdf
pbasdf

Reputation: 21536

From the Core Data Programming Guide, Performance section:

Fetch Predicates

How you use predicates can significantly affect the performance of your application. If a fetch request requires a compound predicate, you can make the fetch more efficient by ensuring that the most restrictive predicate is the first, especially if the predicate involves text matching (contains, endsWith, like, and matches). Correct Unicode searching is slow. If the predicate combines textual and nontextual comparisons, it is likely to be more efficient to specify the nontextual predicates first; for example, (salary > 5000000) AND (lastName LIKE 'Quincey') is better than (lastName LIKE 'Quincey') AND (salary > 5000000). For more about creating predicates, see Predicate Programming Guide.

So, yes, it seems evaluation of the predicates is optimised as you would expect. Much of that will depend on how SQLite optimises the corresponding WHERE clause (assuming you are using an SQLite store).

Upvotes: 2

Related Questions