I have some theoretical question to ask about Core Data and sum function.
I try to sum values from Core Data table with three ways.
fetch all and use expression to sum it up :
NSArray * array1 = [self getAll:self.managedObjectContext];
int sum = [[array1 valueForKeyPath:@"@sum.sum"] intValue];
fetch all 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 sum 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
for 1.000.000 data --> 19.2 s
), the for 1.000.000 data --> 3.54 s
) and the for 1.000.000 data --> 0.3 s
)Why is this?
If I understand right even core data need to go through all 1.000.000
datas and sum it. Is this because use more cores if there are available?
No CoreData doesn't do the summing on it's own - it delegates that to it's backing sqllite database which is optimized for things like that.
Basically CoreData sends a select SUM(sum) from table;
to it's db and it's performed there.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With