> 文章列表 > 【C++容器】vector、map、hash_map、unordered_map四大容器的性能分析【2023.02.28】

【C++容器】vector、map、hash_map、unordered_map四大容器的性能分析【2023.02.28】

【C++容器】vector、map、hash_map、unordered_map四大容器的性能分析【2023.02.28】

摘要

vector是标准容器对数组的封装,是一段连续的线性的内存。map底层是二叉排序树。hash_map是C++11之前的无序map,unordered_map底层是hash表,涉及桶算法。现对各个容器的查询与”插入“性能做对比分析,方便后期选择。

测试方案

测试与开发环境

编译器:QT5.6.3

系统:win11

CPU:i5-12500

内存:DDR4 8G 型号:4ATF1G64AZ-3G2F1

编译:release选项

代码设计

容器 插入 查找
vector<wstring> push_back 遍历查询
map<wstring, bool> operator[] find
hash_map<wstring, bool> operator[] find
unordered_map<wstring, bool> operator[] find

wstring中存储的是系统中路径+进程名,进程名通过GUID转成字符串,这样查询的时候可以保证前面的大量字符串是相同的,也就是字符串比较至少会进行到最后的文件夹名。格式类似如下:

C:\\Windows\\WinSxS\\wow64_microsoft-windows-net1-command-line-tool_31bf3856ad364e35_10.0.22621.674_none_f3295365522a1782{F9168C5ECEB24faaB6BF329BF39FA1E4}.exe

源码

//0积分免费下,有错误欢迎指出
链接:https://pan.baidu.com/s/1QtSYeI5ZPpWZJ5_G7F11xg?pwd=65vy 
提取码:65vy

结果

插入性能

【C++容器】vector、map、hash_map、unordered_map四大容器的性能分析【2023.02.28】

查找性能

【C++容器】vector、map、hash_map、unordered_map四大容器的性能分析【2023.02.28】

总结

四个容器,占用内存其实差不太多,至少我插入20000条数据差别不大。

插入的话性能hash_map和unordered_map差,hash_map最差。map插入最快。

查找的话vector最差,hash_map和unordered_map好,hash_map最好,map的性能也不错。

注意:插入的时候hash_map与unordered_map存在耗时峰值,这个应该是数据拷贝导致。如果插入密集的程序,用这两个容器可能导致程序性能不稳定。