unordered_map 与地图与数组 - 内存分析
unordered_map Vs map Vs array - Memory analysis
正如标题所说,我想知道unordered_map
、map
和array
之间的内存差异。
例:
unordered_map <long long , int> a;
map <long long , int> b;
long long c[1000000];
a
和b
有 1000000 个存储的元素。
我想让它尽可能简单。我在互联网上搜索,没有找到正确的答案。我发现map
和unordered_map
比array
使用更多的内存,但我不知道如何处理它。
编辑:如何处理内存差异,例如如果我存储完全相同的2个元素,内存差异是什么。
自 C++11 起,标准库容器支持有状态分配器:您可以传递一个分配器类型,该分配器类型记录分配的数据量并跟踪最大使用量。您还需要考虑对象大小,因为对于数组来说,实际上没有分配器,因为数组是内置实体。
下面是一个示例:
#include <iostream>
#include <functional>
#include <memory>
#include <map>
#include <unordered_map>
#include <vector>
using namespace std;
static constexpr long total_size = 1000000;
template<typename T>
class CountingAllocator
{
public:
shared_ptr<size_t> d_max = make_shared<size_t>(0u);
using value_type = T;
using pointer = T*;
CountingAllocator() = default;
template <typename S>
CountingAllocator(CountingAllocator<S> const& other): d_max(other.d_max) {}
size_t size() const { return *d_max; }
T* allocate(size_t size) {
size *= sizeof(T);
*d_max += size;
return reinterpret_cast<T*>(operator new(size));
}
void deallocate(void* ptr, size_t) {
operator delete(ptr);
}
friend bool operator== (CountingAllocator const& c0, CountingAllocator const& c1) {
return c0.d_max == c1.d_max;
}
friend bool operator!= (CountingAllocator const& c0, CountingAllocator const& c1) {
return !(c0 == c1);
}
};
template <typename T>
void size(char const* name) {
CountingAllocator<typename T::value_type> allocator;
T m(allocator);
for (int i = 0; i != total_size; ++i) {
m[i] = i;
}
cout << name << "=" << allocator.size() << "n";
}
int main() {
size<map<long, long long, less<int>, CountingAllocator<pair<long const, long long>>>>("map");
size<unordered_map<long, long long, hash<long>, equal_to<long>, CountingAllocator<pair<long const, long long>>>>("unordered_map");
cout << "array=" << sizeof(long long[total_size]) << "n";
return 0;
}
在 ideone 上带有叮当声,这打印(不过,我在这里对齐了尺寸(:
map= 48000000
unordered_map=40654880
array= 8000000
当然,该阵列的占用空间最小(每个元素开销为零(。我很惊讶unordered_map
每个元素的平均开销比map
要小。除了数据之外使用5个单词似乎有点过分。
相关文章:
- 将字符串存储在c++中的稳定内存中
- C++ 指针的内存地址和指向数组的内存地址如何相同?
- 为什么不;名字在地图上是按顺序排列的吗
- Win32编译器选项和内存分配
- 当vector是tje全局变量时,c++中vector的内存管理
- 带内存和隔离功能的SQLite
- 是否可以通过C++扩展强制多个python进程共享同一内存
- 基于多个条件处理地图中的所有元素
- 迭代时从向量和内存中删除对象
- 在C++中打印指向不同基元数据类型的指针的内存地址
- unordered_map 与地图与数组 - 内存分析
- 需要知道如何从本机 HAL 将地图存储在 android 持久内存中
- 内存效率标准::地图替代
- 如何在CPU和内存中优化C 中的重型地图插入
- 这个用于地图的参考计数内存管理器的概念好吗?
- 在插入C STL地图之前,我需要使用新的内存分配内存
- 使用std :: String键在共享内存中升级无序地图
- 访问地图元素会增加其分配的内存大小
- 导致Seg故障的地图.如何增加内存
- 内存管理的想法,标准::地图,提升::shared_ptr