std::map用于key-value式的查询,增加map的效率的办法:
1. 使用emplace代替insert. 直接构建key-value对象
map.emplace(std::piecewise_construct,
std::forward_as_tuple(i,"x"),
std::forward_as_tuple(i));
2. key减少对std::string的依赖
std::string可能会发生对动态内存的申请。
class Key {
int a_;
std::string b_;
public:
Key(int a, std::string b) :a_(a), b_(b) {}
bool operator<(const Key& other) {
if (a_ != other.a_) {
return a_ < other.a_;
}
else {
if (b_ != other.b_) {
return b_ < other.b_;
}
else {
return false;
}
}
}
};
3. 为了保证严格弱排序,小于操作符的实现注意:当对象值相等时,永远返回false。
为了实现这一点,例2中的operator<已经非常复杂了,当考虑进入更多成员时,将极易出错。现在有了std::tie解决这个问题
class Key {
int a_;
std::string b_;
std::string c_;
public:
Key(int a, std::string&& b, std::string&& c)
:a_(a), b_( std::move(b) ), c_(std::move(c))
{}
bool operator<(const Key& other) {
return std::tie(a_, b_, c_) < std::tie(other.a_, other.b_, other.c_);
}
};
4. 自定义分配器,通过boost内存池获取
实测并未增加效率
#include <boost/pool/pool_alloc.hpp>
typedef std::map<Key, int >::value_type pair_type;
typedef std::map<Key, int, less_op, boost::pool_allocator<pair_type> > map_type;
map_type map;