Core-data, a predicate and a loop
Just been doing some work in which we needed to parse some data in the thesnowsite.com database. Basically, the problem was to take the data and then do a series of ‘internal’ consistency and comparison checks. Essentially there were several hundred pieces of data needed to be compared against themselves.
To put it in simple terms, if there were 100 pieces of data (in this case there were actually many more than that) then the comparison would be 100 by 100, i.e. 10,000 ‘checks’.
Basically, two ways to do this. One, loop through the data with one loop taking the data, then the nested loop running through ALL the data to do the comparison; or two, use core-data and a ‘predicate’. Therefore it was decided to do a ‘check’ using a smaller data set to see which approach would be the fastest.
So, the two methods.
The ‘loop’:
NSArray containing 100 items
for (i = 0; i < 100; i++)
for (x = 0; x < 100; x++)
compare item i of NSArray with item x of NSArray and
if match do something
end loop
end loop
The ‘fetch’:
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
NSEntityDescription *entity = [NSEntityDescription entityForName:
@"the_data" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:
@"value_pne >= %f AND value_two <= %f AND d_type == 1",
valOne, valTwo];
[request setPredicate:predicate];
NSError *error = nil;
NSArray *array = [managedObjectContext executeFetchRequest:request
error:&error];
look at array and if contains items (i.e. matches) do something...
What really surprised me was how much faster the ‘loop’ approach was at this task. A big surprise. Hence the task was tackled using a loop… job done!