Is emplace suitable for base types?

Let's say I have map<int, int> :

 std::map<int, int> map; map.emplace(1, 2); map.insert({3, 4}); 

Will there be a difference between the two calls?

In the first call, two integers will be copied by value to the emplace function, and then again to the constructor std::pair<int, int> . In the second call, two integers will be copied by value to the constructor std::pair<int, int> , and then copied by value to the internal std::pair<int, int> again as members of the first pair.

I understand the benefits of emplace for types like std::string , where they will be copied by value in the second call and completely moved in the first, but is there any use in using emplace in the described situation

+7
c ++ containers c ++ 14
source share
1 answer

Emplace is slower if there is a chance that emplace will not work (the key is already present).

This is because emplace needs to select a node and build a pair<Key const, Value> , and then extract the key from this node and check if this key is present, then release the node if the key is already present. On the other hand, insert can extract the key from the passed value that needs to be inserted, so you do not need to select the node if the insert failed. See: emplace's performance is worse than checking and then emplace .

To fix this, C ++ 17 adds a try_emplace(const key_type& k, Args&&... args) member try_emplace(const key_type& k, Args&&... args) (etc.)

If successful, there is no real difference between the two cases; the order of operations is different, but it will not affect performance in any predictable way. The code size will still be slightly larger for the emplace option, as it should be ready for more work in the event of a crash.

+11
source share

All Articles