Anubis
Anubis

Reputation: 7435

Performance of std::map index operator vs insert method

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?

Upvotes: 2

Views: 396

Answers (1)

bartop
bartop

Reputation: 10315

Unless measured, saying anything about performance lose/gains is kinda pointless. Sure, first version is theoretically faster but only measurement can show how relevant theory is.

Saying that - in my opinion the point of the change is making the logic explicit - assign value or insert if value does not exists in map. The usage of operator[] with std::map is one of the more nasty quirks of the language. Since C++17 there is dedicated method for this - insert_or_assign which is as fast as emplace or insert.

Upvotes: 3

Related Questions