2011-07-19 63 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毫秒 –