使用NSMutableDictionary优化for循环

时间:2011-07-19 13:27:25

标签: objective-c ios

我有一个NSMutableDictionary,它包含一个MPMediaItem,以及它的键的标题字符串。我目前在字典中有1,777项。

我在字典中循环,寻找与提供的NSString的模糊匹配。我怎样才能加快速度?每次运行大约需要6秒钟。

我刚刚进入循环本身

@autoreleasepool {
        float currentFoundValue = 1000.0;
        NSMutableArray *test;
        MPMediaItemCollection *collection;
        float match;
        for(id key in artistDictionary)
        {
            NSString *thisArtist = key;
            int suppliedCount = [stringValue length];
            int keyCount = [thisArtist length];
            if(suppliedCount > keyCount)
            {
                match = [StringDistance stringDistance:thisArtist :stringValue];
            } else {
                match = [StringDistance stringDistance:stringValue :thisArtist];
            }
            if(match < currentFoundValue)
            {
                currentFoundValue = match;
                test = [artistDictionary objectForKey:thisArtist];
                collection = [[MPMediaItemCollection alloc] initWithItems:test];
            }
        }

...

2 个答案:

答案 0 :(得分:2)

请参阅-enumerateKeysAndObjectsWithOptions:usingBlock:,并使用NSEnumerationConcurrent选项。

答案 1 :(得分:0)

你有两个性能布道:

  1. 如果只需要创建最后一个迭代,则可能会为每次迭代重建一次MPMediaItemCollection实例。
  2. - 当需要枚举字典的键和值时,[NSDictionary enumerateKeysAndObjectsWithOptions:usingBlock:]会快得多。
  3. 改变成这样的东西:

    float currentFoundValue = 1000.0;
    NSMutableArray *test = nil;
    MPMediaItemCollection *collection;
    float match;
    [artistDictionary enumerateKeysAndObjectsWithOptions:NSEnumerationConcurrent
                                              usingBlock:^(id key, id obj, BOOL *stop) 
    {
        NSString *thisArtist = key;
        int suppliedCount = [stringValue length];
        int keyCount = [thisArtist length];
        if(suppliedCount > keyCount)
        {
            match = [StringDistance stringDistance:thisArtist :stringValue];
        } else {
            match = [StringDistance stringDistance:stringValue :thisArtist];
        }
        if(match < currentFoundValue)
        {
            currentFoundValue = match;
            test = obj;
        }
    }];
    collection = [[MPMediaItemCollection alloc] initWithItems:test];