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?
CodePudding user response:
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;
}