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().
Chances are that the first will be ‘epsilon-faster’, because of this (from 23.3.1 in the standard) :
In the first version, you directly construct the appropriate type expected by
std::map<K,V>::insertIn the second version, a conversion using
std::pairtemplate constructor is involved. Indeed,std::make_pairwill most likely deduce its template arguments toKeyTypeandValType, thus returning astd::pair<KeyType, ValType>.This does not match the parameter type of
std::map<K,V>::insert, which isstd::pair<const KeyType, ValType>(the difference being theconst-qualified first). Thestd::pairconversion constructor will be used to create astd::pair<const K, V>from thestd::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).