stl中unordered_map的insert/clear 性能问题解决
来源:互联网 发布:csbte源码 编辑:程序博客网 时间:2024/05/21 04:23
最近项目中使用到stl unordermap,当map存储的key数量上升到10的6次-7次甚至8次以上时,unordermap的insert接口性能有严重瓶颈
下面是测试代码:
int main() { std::unordered_map<int, int> t; for (int i = 0; i <= 10000000; ++i) { t.insert(make_pair(i, 1)); }}以上 运行时间
real 0m5.231suser 0m4.888ssys 0m0.331s
原因是随着插入元素增多,insert过程中发生了碰撞,碰撞开链到一定的阈值,触发了增加bucket,进而触发了rehash,打印bucket_size可以看到bucketsize一直在增加,代价非常大
unorderedmap提供了reserve和rehash两个接口
reserve可以用来预留元素个数,rehash根据提供的元素个数预留足够的bucket数目
修改后代码
int main() { std::unordered_map<int, int> t; t.reserve(10000000); t.rehash(10000000); for (int i = 0; i <= 10000000; ++i) { t.insert(make_pair(i, 1)); }}
运行时间如下:
real 0m3.823suser 0m3.551ssys 0m0.262s
有很大的好转。
另外,map大了,带来的问题就是clear非常耗时,上面的map clear一次,大约在300ms
将clear换成如下代码:
std::unordered_map<int, int> tmp;t.swap(tmp);
时间马上降到微秒级别
Exchanges the contents of the container with those of other. Does not invoke any move, copy, or swap operations on individual elements上面是对swap的说明
swap的时间复杂度是常数,根据说明,可以看出应该是底层内存指针的交换
Removes all elements from the container.Invalidates any references, pointers, or iterators referring to contained elements. May also invalidate past-the-end iterators.上面是对clear的说明,可以看出其时间复杂度是线性的,随元素个数变化,个数多了,挨个销毁,自然就慢了
以上。
0 0
- stl中unordered_map的insert/clear 性能问题解决
- STL中map,unordered_map,multimap的区别
- STL中clear()操作方法的使用细节
- [C++杂记] STL中vector中clear的使用
- STL中vector,find,insert的使用
- STL map与Boost unordered_map 的不同
- STL map和unordered_map的区别
- STL中map,multimap,set,multiset,unordered_map,unordered_multimap,unordered_set,unordered_multiset的实现方法
- STL中map,multimap,set,multiset,unordered_map,unordered_multimap,unordered_set,unordered_multiset的实现方
- boost中unordered_map的用法
- Mysql 中insert语句的性能优化
- STL clear
- STL---哈希map:unordered_map
- STL unordered_map(hash_map)详解
- STL之unordered_map
- STL中map的成员函数insert的返回值
- STL中map的成员函数insert的返回值
- STL中set的insert操作的返回值
- 数据库<8> MySQL的统计函数
- Kibana在项目中的应用
- 字符串数组容易搞混的方法以及地址拆分
- Spring读取配置文件
- 省赛前第四次练习(共7道 未完待续)菜鸟在努力。。。。。
- stl中unordered_map的insert/clear 性能问题解决
- 目录与路径
- python numpy中nonzero()的用法
- 两种用jq实现的轮播图(向左右滑动和淡出效果)
- Problem B: 重载函数:max
- SpringCloud 分布式配置
- LR https接口
- Hibernate级联保存
- mybatis 主键回显