【发布时间】:2018-02-06 20:28:30
【问题描述】:
假设我们有一个昂贵的函数映射 string 到 int 并且想要将结果缓存在一个映射中。
最简单的代码是
int mapStringToIntWithCache(std::string const& s) {
static std::unordered_map<std::string, int> cache;
if (cache.count(s) > 0) return cache[s];
else return cache[s] = myExpensiveFunction(s);
}
但这有 2 次查找。
因此我倾向于写这个
int mapStringToIntWithCache(std::string const& s) {
static std::unordered_map<std::string, int> cache;
size_t sizeBefore = cache.size();
int& val = cache[s];
if (cache.size() > sizeBefore) val = myExpensiveFunction(s);
return val;
}
这只有一个查找,但看起来有点笨拙。有没有更好的办法?
【问题讨论】:
-
第一个 sn-p 不需要两个以上的查找吗?它有两次
count和cache[s] -
@user463035818
count是第一个查找,然后是两个[s]查找之一,但只有一个。所以每次运行两次查找。 -
是的,我没有仔细阅读。我不得不承认我的第一反应是:过早优化。然而,一旦你决定使用缓存,它就不再为时过早......
-
如果您关心性能,请不要通过 const 左值引用传递参数。如果插入发生,这将阻碍从右值
string参数移动。使用,例如,完美转发。
标签: c++ performance dictionary stdmap