std::unordered_map 非常高的内存使用率

2021-12-22 00:00:00 visual-c++ c++ unordered-map

昨天我尝试使用 std::unordered_map 这段代码让我迷惑了它使用了多少内存.

Yesterday i tried to use std::unordered_map and this code confused me how much memory it used.

typedef list<string> entityId_list;
struct tile_content {
   char cost;
   entityId_list entities;
};
unordered_map<int, tile_content> hash_map;

for (size_t i = 0; i < 19200; i++) {
   tile_content t;
   t.cost = 1;
   map[i] = t;
}

所有这部分代码都是在 MS VS2010 中以调试模式编译的.我在我的任务管理器中看到的是大约 1200 kb 的干净"进程,但是在填充 hash_map 后它使用了 8124 kb 的内存.这是 unordered_map 的正常行为吗?为什么要使用这么多内存?

All this parts of code was compiled in MS VS2010 in debug mode. What I've been seen in my task manager was about 1200 kb of "clean" process, but after filling hash_map it uses 8124 kb of memory. Is it normal behavior of unordered_map? Why so much memory used?

推荐答案

unordered_map 结构旨在以一种使添加、删除、查找和无序遍历高效的方式保存大量对象.对于小型数据结构,它并不意味着内存高效.为了避免与调整大小相关的惩罚,它在第一次创建时分配了许多哈希链头.

The unordered_map structure is designed to hold large numbers of objects in a way that makes adds, deletes, lookups, and orderless traverses efficient. It's not meant to be memory-efficient for small data structures. To avoid the penalties associated with resizing, it allocates many hash chain heads when it's first created.

相关文章