I have a theoretical question to ask about Core Data and the sum function.
I am trying to summarize values from a Core Data table in three ways.
extract everything and use the expression to summarize:
NSArray * array1 = [self getAll:self.managedObjectContext];
int sum = [[array1 valueForKeyPath:@"@sum.sum"] intValue];
extract everything and use for loop:
int sum2 = 0;
NSArray * array2 = [self getAll:self.managedObjectContext];
for (Test * t in array2) {
sum2 = sum2 + [t.sum intValue];
}
let Core Data summarize it.
NSArray * array = [self getAllGroupe:self.managedObjectContext];
NSDictionary * i = [array objectAtIndex:0];
id j = [i objectForKey:@"sum"];
(NSArray *)getAllGroupe:(NSManagedObjectContext*)Context{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Test"
inManagedObjectContext:Context];
NSExpressionDescription* ex = [[NSExpressionDescription alloc] init];
[ex setExpression:[NSExpression expressionWithFormat:@"@sum.sum"]];
[ex setExpressionResultType:NSDecimalAttributeType];
[ex setName:@"sum"];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:ex, nil]];
[fetchRequest setResultType:NSDictionaryResultType ];
NSError *error;
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [Context executeFetchRequest:fetchRequest error:&error];
return fetchedObjects;
}
surprisingly
- the path was the slowest (
for 1.000.000 data --> 19.2 s) - the path was faster (
for 1.000.000 data --> 3.54 s) and - the path was the fastest (
for 1.000.000 data --> 0.3 s)
Why is this?
If I understand correctly that even the main data must go through all the 1.000.000data and summarize them. Is it because using more cores if available?
source
share