[英]What's the size of a node in std::map containing an enum - pointer pair
我正在努力減少我的應用程序的 memory 要求,因為我正在考慮從 30 個條目的數組(其中許多是空的 / NULL )移動到 std::Z1D78DC8ED51214E518B5114AE24 作為鍵和值的指針這樣,我將只有我需要的條目。
// I create around 50 million objects of my_class type
class my_class
{
// I want to change this
my_ptr* arr[30];
// to
std::map<enum_type,my_ptr*> my_map;
};
我創建了5000萬個class以上的對象,所以我會有5000萬個這樣的地圖。 我想了解 std::map 的單個節點的大小。我讀到它們是作為紅黑樹實現的,每個節點都會保存指向子節點的指針,所以我猜測子節點至少有 16 個字節,也許8 個字節多用於存儲顏色。 在這里使用 std::unordered_map 更好還是我應該嘗試不同的數據結構?
讀它們被實現為紅黑樹,每個節點都將保存指向子節點的指針
可能還需要一個父指針。
我應該嘗試不同的數據結構嗎?
如果您唯一關心的是 memory 使用,那么您應該使用包含索引和指針的對象向量。
memory有多種用途你可以關心。 該數組具有恆定大小,並且在my_class
數據結構之外沒有分配。 使用 map 可能會導致發生其他分配。 與向量相同。
如果單個 object 更小,您可能會感到滿意——正如@eerorika 指出的那樣,對於一個空的my_class ,一個向量可能是 16 字節my_class
的索引+指針。 無論如何,數組實現都保持 240 字節。 使用object時會怎樣? 插入幾個元素,也許發生了重新分配,你突然得到 memory 碎片,來自底層分配庫的開銷等。
這是一個使用 jemalloc 的malloc_stats_print()
來顯示可能發生的情況的高度不可移植的示例:
#include <malloc_np.h>
#include <stdio.h>
#include <stdlib.h>
#include <map>
struct my_ptr;
struct my_class_arr {
my_ptr *arr[30];
};
struct my_class_map {
std::map<int, my_ptr *> my_map;
};
int main(int argc, char **argv) {
constexpr const int million = 1000000;
printf("Memory usage before:\n");
malloc_stats_print(nullptr, nullptr, nullptr);
if (argc > 1) {
auto *arr = new my_class_arr[million];
arr[17].arr[3] = nullptr;
} else {
auto *map = new my_class_map[million];
map[17].my_map[3] = nullptr;
}
printf("Memory usage after:\n");
malloc_stats_print(nullptr, nullptr, nullptr);
return 0;
}
統計信息在程序啟動時打印,並在分配一百萬個對象后打印。 我相信(非常冗長)output 中的Allocated行是最相關的,只需在沒有參數的情況下運行數組方法即可。 或使用 map 結構的參數。
使用clang,無優化(注意無優化的無用:):
./a.out 2>&1 | grep ^Allocated
Allocated: 69640, active: 77824, metadata: 4509640 (n_thp 0), resident: 4562944, mapped: 6369280, retained: 2019328
Allocated: 25240896, active: 25276416, metadata: 4551504 (n_thp 0), resident: 29810688, mapped: 33669120, retained: 6176768
對 output 的第二行做一個小表,用於各種組合:
或者,更籠統地說:測量(針對您的特定用途),不要猜測。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.