unordered_map 与地图与数组 - 内存分析

unordered_map Vs map Vs array - Memory analysis

本文关键字:内存 地图 map unordered 数组      更新时间:2023-10-16

正如标题所说,我想知道unordered_mapmaparray之间的内存差异。

例:

unordered_map <long long , int> a;
map <long long , int> b;
long long c[1000000];

ab有 1000000 个存储的元素。

我想让它尽可能简单。我在互联网上搜索,没有找到正确的答案。我发现mapunordered_maparray使用更多的内存,但我不知道如何处理它。

编辑:如何处理内存差异,例如如果我存储完全相同的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个单词似乎有点过分。