Objective-C中的高效循环 [英] Efficient looping in objective-c
问题描述
我使用解析作为后端服务,但在本示例中,我创建了两个示例数组(songs
和ratings
)来模仿我的后端架构. songs
由将填充我的应用程序表的歌曲数据组成. ratings
由当前用户的歌曲评分组成.
I'm using Parse as my backend service, but for this example I created two sample Arrays (songs
and ratings
) that mimic my backend schema. songs
consists of song data that will populate my app's table. ratings
consist of the current user's ratings of songs.
最终,我需要遍历songs
和ratings
以便将userRating
嵌入到相应的songs
词典中.我在下面包含了我的循环代码.可以更有效地做到这一点吗?我担心如果ratings
对象太多,将会花费太长时间.
Ultimately, I need to loop through songs
and ratings
to embed the userRating
in the respective songs
dictionary. I've included my looping code below. Can this be done more efficiently? I'm worried it will take too long if there are too many ratings
objects.
NSMutableArray *songs = [@[ @{
@"objectId" : @"111",
@"title" : @"Song Title" },
@{
@"objectId" : @"222",
@"title" : @"Song Title"
} ] mutableCopy];
NSMutableArray *ratings = [@[ @{
@"objectId" : @"999",
@"parentObjectId" : @"111",
@"userRating" : @4
} ] mutableCopy];
for (NSInteger a = 0; a < songs.count; a++) {
NSMutableDictionary *songInfo = [songs objectAtIndex:a];
NSString *songObjectId = [songInfo objectForKey:@"objectId"];
NSNumber *userRating = @0;
for (NSInteger i = 0; i < ratings.count; i++) {
NSDictionary *userRatingInfo = [ratings objectAtIndex:i];
NSString *parentObjectId = [userRatingInfo objectForKey:@"parentObjectId"];
if ([parentObjectId isEqualToString:songObjectId]) {
userRating = [userRatingInfo objectForKey:@"userRating"];
}
}
[songInfo setObject:userRating forKey:@"userRating"];
}
推荐答案
构建评分词典,而不要产生内在循环.您的时间复杂度将从n * m变为n + m,因为字典查找将分摊固定时间:
Build a dictionary of ratings instead of having an inner loop. Your time complexity will go from n*m to n+m since dictionary lookups are amortized constant time:
NSMutableDictionary* ratingsDict = [NSMutableDictionary dictionaryWithCapacity:ratings.count];
for (NSDictionary* rating in ratings) {
NSString *parentObjectId = [rating objectForKey:@"parentObjectId"];
[ratingsDict setObject:rating forKey:parentObjectId];
}
for (NSMutableDictionary* song in songs) {
NSString *songObjectId = [song objectForKey:@"objectId"];
NSNumber *userRating = [ratingsDict objectForKey:songObjectId];
if (userRating)
[song setObject:userRating forKey:@"userRating"];
}
这篇关于Objective-C中的高效循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!