CoreData总性能 [英] CoreData Sum Performance
问题描述
对于核心数据和求和函数,我有一些理论上的问题。
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];
}
让Core Data对其求和。
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;
}
令人惊讶的是
- 方式最慢(对于1.000.000数据<< c $ c>-> 19.2 s ) ,
- 的速度更快(对于1.000.000数据,
-> 3.54 s
)和 - 方式最快(对于1.000.000数据<< c $ c>-> 0.3 s )
- way was the slowest (
for 1.000.000 data --> 19.2 s
), the - way was faster (
for 1.000.000 data --> 3.54 s
) and the - way was the fastest (
for 1.000.000 data --> 0.3 s
)
为什么这样?
如果我理解正确,甚至核心数据都需要遍历所有 1.000.000
数据并将其求和。这是因为要使用更多的内核(如果有)?
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?
推荐答案
没有CoreData自己不进行求和-委托它支持sqllite数据库,该数据库针对此类事情进行了优化。
基本上,CoreData从表中发送 select SUM(sum);
到它的数据库,并在那里执行。
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.
这篇关于CoreData总性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!