Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is emplace for basic types worth it?

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

std::map<int, int> map;

map.emplace(1, 2);
map.insert({3, 4});

Will there be any difference between the two calls?

In the first call, the two integers will be copied by value to the emplace function and then again to the std::pair<int, int> constructor. In the second call, the two integers will be copied by value to the std::pair<int, int> constructor and then be 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 would be copied by value in the second call and moved all the way in the first one, but is there any benefit in using emplace in the situation described?

like image 854
coyotte508 Avatar asked Jun 02 '16 14:06

coyotte508


1 Answers

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

This is because emplace is required to allocate a node and construct the pair<Key const, Value> into it, then extract the key from that node and check whether the key is already present, then deallocate the node if the key is already present. On the other hand insert can extract the key from the passed value to be inserted, so does not need to allocate a node if the insert would fail. See: performance of emplace is worse than check followed by emplace.

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

In case of success, there is no real difference between the two cases; the order of operations is different, but that will not affect performance in any predictable fashion. Code size will still be slightly larger for the emplace variant, as it has to be ready to perform more work in the failure case.

like image 145
ecatmur Avatar answered Sep 23 '22 07:09

ecatmur