2011-07-19 9 views
0

私は、MPMediaItemを含むNSMutableDictionaryとそれのキーの文字列を持っています。私は現在、辞書に1,777項目あります。NSMutableDictionaryを使用してforループを最適化する

私は提供された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

申し訳ありません - 私はそれを実装しました。それは合計時間から約1秒シェービングしています。それが私がここでできることすべてについてですか? –

+0

楽器を使用して時間を使い切っているかどうかを確認するには、私の推測では、文字列距離の計算が最も気になるものです。 1700要素はそんなにあまりありません。 – DarkDust

0

あなたは、2人の性能ブートルの首を持っている:

  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を実装しました。それはおそらく500msを節約しています。注意すべきことは、これらの変数にはブロック内のアクセスに__blockの割り当てが必要です。私はhashKeysと他のものを実装して、合計で約750msの検索結果を得ました –

関連する問題