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
The third one is the best choice (IMHO), but 2, 3 and 4 are equal.
// 3) Assignment using member function insert() and "value_type()"
Foo.insert(map::value_type("Bar", 12345));
Why I think the third one is the best choice: You're performing only one operation to insert the value: just inserting (well, there's a search too) and you can know if the value was inserted, checking the second
member of the return value and the implementation grants to not overwrite the value.
The use of the value_type
has advantages too: you don't need to know the mapped type or key type so is useful with template programming.
The worst (IMHO) is the first one:
// 1) Assignment using array index notation
Foo["Bar"] = 12345;
You're calling the std::map::operator[]
wich creates an object and returns a reference to it, then the mapped object operator =
is called. You're doing two operations for the insertion: first the insertion, second the asignation.
And it have another problem: you don't know if the value has been inserted or overwrited.