简体   繁体   English

std :: map中的内存分配

[英]Memory Allocation in std::map

I am doing a report on the various C++ dictionary implementations (map, dictionary, vectors etc). 我正在撰写有关各种C ++词典实现(地图,词典,向量等)的报告。

The results for insertions using a std::map illustrate that that the performance is O(log n). 使用std :: map插入的结果说明性能为O(log n)。 There are also consistent spikes in the performance. 性能上也有持续的峰值。 I am not 100% sure what's causing this; 我不是100%知道是什么原因造成的; I think they are caused by memory allocation but I have been unsuccessful in finding any literature / documentation to prove this. 我认为它们是由内存分配引起的,但是我一直没有找到任何文献/文档来证明这一点。

Can anyone clear this matter up or point me in the right direction? 谁能解决这个问题或为我指明正确的方向?

Cheers. 干杯。

You are right: it is O(log n) complexity. 您是对的:这是O(log n)复杂度。 But this is due to the sorted nature of map (normally binary tree based). 但这是由于map的排序性质(通常基于二叉树)。

Also see http://www.sgi.com/tech/stl/UniqueSortedAssociativeContainer.html there is a note on insert. 另请参见http://www.sgi.com/tech/stl/UniqueSortedAssociativeContainer.html,其中有关于插入的说明。 It's worst case is O(log n) and amortized O(1) if you can hint where to do the insert. 最糟糕的情况是O(log n)和摊销O(1),如果您可以暗示在哪里进行插入。

Maps are normally based on binary trees and need to be balanced to keep good performance. 映射通常基于二叉树,需要进行平衡以保持良好的性能。 The load spikes you are observing probably correspond to this balancing process 您观察到的负载峰值可能与此平衡过程相对应

The empirical approach isn't strictly necessary when it comes to STL. 对于STL,经验方法并不是绝对必要的。 There's no point in experimenting when the standard clearly dictates the minimal complexity of operations such as std::map insertion. 当标准明确规定了操作(例如std :: map插入)的最小复杂性时,没有任何实验意义。

I urge you to read the standard so you're aware of the minimal complexity guarantees before continuing with experiments. 我敦促您阅读该标准,以便在继续实验之前了解最小的复杂性保证。 Of course, there might be bugs in whatever STL implementation you happen to be testing; 当然,您碰巧要测试的任何STL实现中都可能存在错误。 but the popular STLs are pretty well-debugged creatures and very widely used, so I'd doubt it. 但是流行的STL是经过充分调试的生物,并且用途非常广泛,因此我对此表示怀疑。

If I remember correctly, std::map is a balanced red-black tree. 如果我没记错的话,std :: map是一棵平衡的红黑树。 Some of the spikes could be caused when the std::map determines that the underlying tree needs balancing. 当std :: map确定基础树需要平衡时,可能会导致某些峰值。 Also, when a new node is allocated, the OS could contribute to some spikes during the allocation portion. 同样,在分配新节点时,OS可能会在分配部分造成一些峰值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM