LoginSignup
2

More than 5 years have passed since last update.

mapの検索はfindとcountとどっちが早いんだろう

Posted at

stlのmapの検索でcountの方が視覚的にわかりやすいソースになっていいよ!という記事を見かけた。
でも、findの方が見つけたら終了しそうだから、早くて、推奨されるはずでは…、と思い、試した。
※stlのソースとかは見てないです。すみません。

test.cpp

    // 速度を判定する
    // map_testには100程度の要素が格納されていますよ。pairがkeyという変わったmapですみません。
    std::pair<wstring,wstring> a = make_pair(L"mememe",L"aaa");

    // 各測定で、時刻をログで出力しました。そこらへんは割愛したソースですが。
    // 測定開始
    for(int i = 0;i< 1000;i++)
    {
         if (map_test.find(a) == map_test.end())
         {
             // 探すだけで処理はしないよ
         }
    }
    // 測定終了

    // 測定開始
    for(int i = 0;i< 1000;i++)
    {
         if (map_test.count(a) == 0)
         {
             // 探すだけで処理はしないよ
         }
    }
    // 測定終了

    a = make_pair(L"mememe",L"sss");    //見つからないパターン

    // 測定開始
    for(int i = 0;i< 1000;i++)
    {
         if (map_test.find(a) == map_test.end())
         {
             // 探すだけで処理はしないよ
         }
    }
    // 測定終了

    // 測定開始
    for(int i = 0;i< 1000;i++)
    {
         if (map_test.count(a) == 0)
         {
             // 探すだけで処理はしないよ
         }
    }
    // 測定終了

測定結果としては、要素数の関係か大差はなかったです。
気持ち、findの方が早いくらいで…。
key=文字、value=数値のマップだったらまた変わったかもしれませんね。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2