std::vector-like class optimized to hold a small number of items [duplicate]

隐身守侯 提交于 2019-12-03 22:34:38

LLVM has a class for that called SmallVector.

In a non-time-critical part of your code, perform: m_vLinks.reserve(1);. That way, in the time-critical part, there will typically be no dynamic allocation.

My first attempt would be to optimize the memory allocator. Naive malloc implementations are not too efficient, you may want to try tcmalloc or jemalloc.

My second attempt would be to change the allocator. Howard Hinnant has demonstrated how to use a stateful allocator that has some memory preallocated on the stack. This is only Standard compliant in C++11, but may already be supported.

My third attempt would be to change the code and pre-allocate the memory if possible. Instead of building the vector anew each time, you could keep it around: its capacity will not diminish and so subsequent uses won't allocate memory.

There are few chances that a homebrew implementation would match the speed of the std::vector<T> classes, as many of its methods have been tuned for maximum performance.

I generally use std::list for these cases. The O(N) operations in std::list don't hurt me when N==1.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!