我应该担心 std::vector 的内存碎片吗?
我应该担心 std::vector 的内存碎片吗?如果是这样,有没有办法帮助预防它?我并不总是预测我的程序会在 PC 上运行,它们也可能会在嵌入式设备/游戏机上运行,所以我不会总是能够依赖虚拟内存.
Should I worry about memory fragmentation with std::vector? If so, are there ways to help prevent it? I don't always predict for my programs to be running on a PC, they may also be running on embedded devices/game consoles, so I won't always be able to rely on virtual memory.
再说一次,我相信使用动态大小的数组而不是静态数组会更有效,这样内存只会在需要时分配.它还可以简化我的程序设计过程.有没有办法有效地实现这一目标?
Then again I believe it would be more efficient to use a dynamically sized array rather than a static array, so that memory would only be allocated if needed. It would also simplify my programs' design process. Are there ways to achieve this efficiently?
感谢您的建议!
std::deque
或许可以解决您的疑虑.它为您提供了与 std::vector
类似的接口,但在碎片内存的情况下效果更好,因为它分配了几个小数组而不是大数组.在某些方面,它实际上比 std::vector
效率低,但对于您的情况,这可能是一个很好的权衡.
The answer to your worries may be std::deque
. It gives you a similar interface to that of std::vector
, but works better with fragmented memory, since it allocates several small arrays instead of a large one. It is actually less efficient than std::vector
in some aspects, but for your case it may be a good trade-off.