How can i estimate memory usage of std::map?

前端 未结 7 661
被撕碎了的回忆
被撕碎了的回忆 2020-11-29 03:06

For example, I have a std::map with known sizeof(A) and sizeof(B), while map has N entries inside. How would you estimate its memory usage? I\'d say it\'s something like

7条回答
  •  醉梦人生
    2020-11-29 04:05

    The estimate would be closer to

    (sizeof(A) + sizeof(B) + ELEMENT_OVERHEAD) * N + CONTAINER_OVERHEAD
    

    There is an overhead for each element you add, and there is also a fixed overhead for maintaining the data structure used for the data structure storing the map. This is typically a binary tree, such as a Red-Black Tree. For instance, in the GCC C++ STL implementation ELEMENT_OVERHEAD would be sizeof(_Rb_tree_node_base) and CONTAINER_OVERHEAD would be sizeof(_Rb_tree). To the above figure you should also add the overhead of memory management structures used for storing the map's elements.

    It's probably easier to arrive at an estimate by measuring your code's memory consumption for various large collections.

提交回复
热议问题