向地图分配值的最有效方法 [英] Most efficient way to assign values to maps
问题描述
哪种方法为地图分配值最有效?还是它们都针对同一代码进行了优化(在大多数现代编译器上)?
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 index notation
Foo["Bar"] = 12345;
// 2) Assignment using member function insert() and STL pair
Foo.insert(std::pair<string,int>("Bar", 12345));
// 3) Assignment using member function insert() and "value_type()"
Foo.insert(map<string,int>::value_type("Bar", 12345));
// 4) Assignment using member function insert() and "make_pair()"
Foo.insert(std::make_pair("Bar", 12345));
(我知道我可以进行基准测试并检查编译器的输出,但是现在出现了这个问题,我手边只有我的手机...呵呵)
(I know I could benchmark and check compiler output, but this question arose now and the only thing I have close at hand is my mobile phone... hehe)
推荐答案
首先,[]
和insert
之间存在语义差异:
First, there are semantic differences between []
and insert
:
-
[]
将替换旧值(如果有) -
insert
将忽略新值(如果已经存在旧值)
[]
will replace the old value (if any)insert
will ignore the new value (if an old value is already present)
因此,将两者进行比较通常是没有用的.
therefore comparing the two is useless in general.
关于插入版本:
-
std::map<std::string, int>::value_type
是std::pair<std::string const, int>
,所以3和4之间没有(重要)差异 -
std::make_pair("Bar", 12345)
比std::pair<std::string, int>("Bar", 12345)
便宜,因为std::string
类型是完全成熟的类,可以对副本进行操作,而"Bar"
只是字符串文字(因此只是指针副本);但是,由于最后您确实需要创建std::string
...,这将取决于编译器的质量
std::map<std::string, int>::value_type
isstd::pair<std::string const, int>
so no (important) difference between 3 and 4std::make_pair("Bar", 12345)
is cheaper thanstd::pair<std::string, int>("Bar", 12345)
because thestd::string
type is a full fledged class with operations to do on copy and"Bar"
is just a string literal (thus just a pointer copy); however since at the end you do need to create thestd::string
... it will depend on the quality of your compiler
通常,我会建议:
-
[]
用于更新 -
insert(std::make_pair())
用于忽略重复项
[]
for updatinginsert(std::make_pair())
for ignoring duplicates
std::make_pair
不仅简短,而且还遵守DRY准则:请勿重复自己.
std::make_pair
is not only shorter, it also respects the DRY guideline: Don't Repeat Yourself.
为了完整起见,最快(也是最简单)的方法是 emplace
(C ++ 11已启用):
For completeness though, the fastest (and easiest) would be emplace
(C++11 enabled):
map.emplace("Bar", 12345);
它的行为是insert
的行为,但是它就地构造了新元素.
Its behavior is that of insert
, but it constructs the new element in-place.
这篇关于向地图分配值的最有效方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!