2011-07-19 61 views
0

我有一个NSMutableDictionary包含MPMediaItem和它的标题的字符串是它的关键。我目前在词典中有1,777项。优化循环与NSMutableDictionary

我正在循环查找与提供的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]; 
      } 
     } 

...

+0

我发现objectForKey是一个糟糕的罪魁祸首这里。 stringDistance方法非常快。 –

回答

2

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

+0

好吧 - 我实现了这一点,它总共花费了大约一秒的时间。这就是我能在这里做的一切吗? –

+0

使用仪器来看看什么是用尽时间,我的猜测是你的弦距离计算是你应该最关心的。 1700个元素并不多。 – DarkDust

0

你有两种表现布特尔脖子:

  1. 你可能重现MPMediaItemCollection实例一次每次迭代,只需要创建最后一个的时候。
  2. - [NSDictionary enumerateKeysAndObjectsWithOptions:usingBlock:]在需要枚举字典的键和值时要快得多。

变成这样的事情:

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]; 
+0

我实现了enumerateKeysAndObjectsWithOptions:usingBlock,它可以节省我500毫秒。有一点需要注意,这些变量需要一个__block赋值来访问块内的内容。我已经实现了hashKeys和其他的东西来搜索到总共约750毫秒 –