Does calling 'count' on a to-many CoreData relationship fault bring all objects in the collection into memory?
Asked Answered
C

2

7

Say I have an Entity 'Employee' with a to-many relationship 'departments' to another entity 'Department'. If I have an instance of an Employee object and the departments collection is currently a fault, what is the most memory efficient way to get the count of departments?

Two obvious options are:

1) calling [myEmployee.departments count];

2) Constructing a fetchRequest to return only the Department objects whose matching 'employee' relationship points to my employee object and then calling countForFetchRequest:

Apart from the memory usage would either one of these methods be non-negligibly faster then the other?

Coeliac answered 6/8, 2011 at 18:10 Comment(0)
D
0

Relationships are not fetched unless you have relationshipKeyPathsForPrefetching.

However, my best advice for you is to always implement your solution in the most straight-forward way, and THEN tackles performance issues later. Humans are notoriously bad at predicting performance problems.

One tool, that is very easy to use, is Instruments, which is included in Xcode.

You can easily run a test using both approaches, and actually compare numbers, rather than just take the opinion of some stranger on SO.

Dituri answered 8/5, 2012 at 14:15 Comment(0)
I
0

First: When the relationship is called the object are loaded as "fault" so the performance is so good.

Second: If you use countForFetchRequest method, the request would be:

NSFetchRequest *f = Departament.fetchRequest;

f.predicate = [NSPredicate predicateWithFormat:@"ANY employees = %@", employe.objectID];

so CoreData must check each department to look the employees. In the practise is more slower.

  • In your case I would use the first option.
  • The situation would be different if the predicate needs properties of the objects, so the first option needs the whole objects without fault. In this case I recommend to use countForFetchRequest, but the best option is compare in the particular case.
Irfan answered 10/11, 2017 at 14:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.