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) :
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With