簡體   English   中英

unordered_map Vs map Vs 數組——內存分析

[英]unordered_map Vs map Vs array - Memory analysis

正如標題所說,我想知道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 上的 clang 打印出來(不過,我在這里對齊了尺寸):

map=          48000000
unordered_map=40654880
array=         8000000

當然,該數組具有最小的占用空間(每個元素開銷為零)。 我很驚訝unordered_map每個元素的平均開銷比map 除了數據之外使用 5 個字似乎有點過分。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM