STD无序的地图储备存储器管理政策

问题描述 投票:0回答:1
一起工作。我正在处理很多插入物。插入量的数量已知。我认为通过使用

reserve

方法和假设它预先分配给所有未来插入物的大量内存来优化内存。  但是,我注意到地图试图分配内存的时间没有任何区别。
举行示例
here
。保留了插入数量和不相同的插入数量的同时分配数量?

有任何方法可以减少分配的数量? #include <string> #include <unordered_map> #include <iostream> #include <vector> using namespace std; inline size_t AllocationCounter = 0; template <typename T> struct my_alloc { using value_type = T; my_alloc(){ }; template <typename U> constexpr my_alloc(const my_alloc<U>& Other) noexcept { } T* allocate(std::size_t n) { AllocationCounter++; return static_cast<T*>(::operator new (n * sizeof(T))); } template <typename... Args> void construct(T* p, Args&&... args) { new (p) T(std::forward<Args>(args)...); } void deallocate(T* p, std::size_t n) noexcept { AllocationCounter --; delete p; } void destroy(T* p) noexcept { p->~T(); } }; void with_reserve() { unordered_map<size_t,size_t, std::hash<size_t>, std::equal_to<size_t>, my_alloc<std::pair<const size_t, size_t>>> m1; m1.reserve(1000); /// <------------------ RESERVATION ? for (size_t i = 0; i < 1000; i++) { m1.insert({i,i}); } printf("With reserve - %llu Allocations\n", AllocationCounter); } void without_reserve() { unordered_map<size_t,size_t, std::hash<size_t>, std::equal_to<size_t>, my_alloc<std::pair<const size_t, size_t>>> m1; for (size_t i = 0; i < 1000; i++) { m1.insert({i,i}); } printf("Without reserve - %llu Allocations\n", AllocationCounter); } int main() { with_reserve(); without_reserve(); }

输出:

With reserve - 1001 Allocations Without reserve - 1001 Allocations
表明:没有储备金的分配数量少于没有。
    

没有。 
STD:: UNORDERED_MAP :: RESISTE仅分配存储桶,而不是节点。

将存储桶数量的数量置于至少容纳至少元素的情况下所需的数字,而不会超过最大负载因子并重新将容器重新调整,即考虑到总的存储桶数量已更改,将元素放入适当的存储桶中。有效致电
c++ templates memory-management std unordered-map
1个回答
0
投票
.

each桶包含一个链接的节点列表,这些节点被分配为插入元素。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.