I recently saw a change in a pull request. I'm wondering whether that does any improvement.
Following is a simplified version.
...
std::map<int, std::string> myMap;
... // map will get updated
void foo(int key, std::string value)
{
myMap[key] = value; // <-- this line gets changed
}
The marked single line was changed as follows.
auto entry = myMap.find(key);
if (entry == myMap.end())
{
myMap.insert(std::make_pair(key, value));
}
else
{
entry->second = value;
}
Maybe the intention was to avoid the creation of an object if key is not present (which seems a valid point). But doesn't a similar temporary object is created in insert() call? Or does some kind of optimization happen here?
In my opinion, both versions should have same performance. But there will be an improvement if emplace() is used instead of insert().
Could someone clarify this if my understanding is wrong?