简体   繁体   English

是否首先使用 std::map::find 进行搜索,然后使用 [] 检索值,通常进行优化?

[英]Is searching first with std::map::find then using [], to retrieve the value, optimised usually?

I find often this pattern in some codebase I work with:我经常在我使用的一些代码库中发现这种模式:

   std::map<std::string, std::string> mymap;

   ...

   if (mymap.find(key) != mymap.end())
   {
       return mymap[key];
   }

I know this can be replaced by我知道这可以替换为

   std::map<std::string, std::string> mymap;

   ...

   auto it = mymap.find(key) 
   if (it != mymap.end())
   {
       return it->second;
   }

But I was wondering if, in practice, the first version would get optimised to not search twice anyway?但我想知道,在实践中,第一个版本是否会得到优化而不是搜索两次?

No it will not be optimized.不,它不会被优化。 The pattern is too high level.模式级别太高。

You could preferentially just do this instead:您可以优先这样做:

 std::map<std::string, std::string> mymap;

   ...

   auto it = mymap.find(key);
   if ( it != mymap.end())
   {
       return it->second;
   }

You can check on the benchmark below:您可以检查以下基准:

int findOptim( int key )
{
   auto it = mymap.find(key); 
   if (it != mymap.end())
   {
       return it->second;
   }
   return -1;
}

int findTrivial( int key ) {
    if ( mymap.find(key) != mymap.end() ) {
        return mymap[key];
    }
    return -1;
}

Benchmark: https://quick-bench.com/q/7mFWe8jlXD7J9GTDMNSiZdcGCgY基准: https://quick-bench.com/q/7mFWe8jlXD7J9GTDMNSiZdcGCgY

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM