开发者

Why is this piece of code so slow? (CoreData & NSSet)

I have an app and I'm implementing full text search. I have 2 enitites: Keywords and Articles with a many-to-many relationship between them. The problematic piece of code is this:

            keywordsInRange = [[[CoreDataManager sharedManager] managedObjectContext]  executeFetchRequest:request error:&err];



            for(Keywords* word in keywordsInRange) {
                NSDate *methodStart = [N开发者_JAVA技巧SDate date];

                [mySet addObjectsFromArray:[word.article allObjects]];

                NSDate *methodFinish = [NSDate date];
                NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:methodStart];
                NSLog(@"Keyword Search Exec Time: %.3f", executionTime);
            }

the output is this:

Keyword Search Exec Time: 0.235  //added 1 article
Keyword Search Exec Time: 0.216  //added 6 articles
Keyword Search Exec Time: 0.211  //etc
Keyword Search Exec Time: 0.205
Keyword Search Exec Time: 0.204

as you can see, to add all articles linked to a keyword in the set takes unexpectedly long time when I test on the device (iPad iOS 4.2.1). When I test in the simulator the times are:

0.029
0.026
0.026
0.026
0.026

Where is the mistake, what can I do to speed things up?


I'm not an expert of CoreData but isn't it lazily loading articles ? If yes, it means there a query executing against the store for every keyword.


Try calling [request setRelationshipKeyPathsForPrefetching:[NSArray arrayWithObject:@"article"]]; before the first line of your code above.

Otherwise, the each iteration in the loop generates a new fetch for the articles although you really only need one.

It is often helpful in this case to use SQLDebug to see the actual SQL statements being generated. To do so, right-click on your executable, click on Get Info, go to the Arguments tab and add -com.apple.CoreData.SQLDebug 1 in "Arguments to be passed on launch".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜