Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++: value_type versus make_pair, which is faster for map insert?

Tags:

typedef map<KeyType, ValType> KVMap; KVMap kvmap;  kvmap.insert( KVMap::value_type( key, val ) ); kvmap.insert( make_pair( key, val ) ); 

Which of the above options to insert to a STL map is always faster? Why?

Note: I am well aware that insert() is faster than using []= for adding (not updating) key-value pairs to a map. Please assume that my query is about adding, not updating. Hence I have restricted it to insert().

like image 698
Ashwin Nanjappa Avatar asked Jan 07 '11 08:01

Ashwin Nanjappa


1 Answers

Chances are that the first will be 'epsilon-faster', because of this (from 23.3.1 in the standard) :

typedef pair<const Key, T> value_type;  [...]  pair<iterator, bool> insert(const value_type& x); 
  • In the first version, you directly construct the appropriate type expected by std::map<K,V>::insert

  • In the second version, a conversion using std::pair template constructor is involved. Indeed, std::make_pair will most likely deduce its template arguments to KeyType and ValType, thus returning a std::pair<KeyType, ValType>.

    This does not match the parameter type of std::map<K,V>::insert, which is std::pair<const KeyType, ValType> (the difference being the const-qualified first). The std::pair conversion constructor will be used to create a std::pair<const K, V> from the std::pair<K, V>.

To be fair, I don't believe you could even measure the difference (and I'm not even sure that popular compilers will actually generate a different code for these).

like image 134
icecrime Avatar answered Oct 03 '22 19:10

icecrime