Which way to assign values to a map is most efficient? Or are they all optimized to the same code (on most modern compilers)?
// 1) Assignment using array ind
1) may be slightly slower than the other methods because std::map::operator[]
first default-creates the object if it doesn't already exist, then returns a reference that you can use operator=
on to set your desired value, i.e. two operations.
2-4) should be equivalent since map::value_type
is a typedef to std::pair
for the same types, and therefore make_pair
is also equivalent. The compiler should treat these identically.
Also note that performance can be increased further if you need to both check for existence (e.g. to perform special logic depending on whether it exists or not) and then also insert it, by using map::lower_bound
to first get a hint to where the element should be, so map::insert
does not have to search the whole map
again:
// get the iterator to where the key *should* be if it existed:
std::map::iterator hint = mymap.lower_bound(key);
if (hint == mymap.end() || mymap.key_comp()(key, hint->first)) {
// key didn't exist in map
// special logic A here...
// insert at the correct location
mymap.insert(hint, make_pair(key, new_value));
} else {
// key exists in map already
// special logic B here...
// just update value
hint->second = new_value;
}