Rendimiento de la suma de datos básicos

I have some theoretical question to ask about Core Data and sum función.

I try to sum values from Datos principales table with three ways.

  1. fetch all and use expression to sum it up :

    NSArray * array1 = [self getAll:self.managedObjectContext];
    int sum = [[array1 valueForKeyPath:@"@sum.sum"] intValue];
  2. 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];
  3. 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"  
        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

  1. way was the slowest (for 1.000.000 data --> 19.2 s), el
  2. way was faster (for 1.000.000 data --> 3.54 s) y el
  3. way was the fastest (for 1.000.000 data --> 0.3 s)

¿Por qué es esto?

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?

preguntado el 12 de febrero de 14 a las 06:02

1 Respuestas

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.

Respondido 12 Feb 14, 07:02

Do you know why is the 1. way slower than 2.-one? - Marko Zadravec

@MarkoZadravec do you execute 1 and 2 in that order on the same context? - dan shelly

I assume that 1 is slower than 2 due because direct property access is probably fast then property access via key value coding - rist

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.