【发布时间】:2014-05-17 22:35:17
【问题描述】:
假设需要一个 固定大小 的缓冲区,是否有大小限制或阈值,这样在该大小限制下,可以使用快速堆栈分配的std::array,高于该大小限制限制最好使用std::vector 并从堆中动态分配内存(因为堆栈内存很宝贵,不应该消耗太多)?
// I think allocating 32 bytes on the stack is just fine.
std::array<BYTE, 32> smallBuffer;
// For 32KB, it's better getting memory from the heap.
std::vector<BYTE> bigBuffer(32*1024);
// Is it better to allocate a 1KB buffer on the stack (with std::array)
// or is it too much, and it's better to allocate on the heap (using std::vector)?
// What about 512 bytes? And 4KB?
// Is there a suggested size threshold?
std::array<BYTE, 1024> buffer;
【问题讨论】:
-
如果您的系统为您提供 8 MiB 的堆栈(Mac OS X 上的默认值;Linux 将类似),那么您可能应该开始担心大约 1 MiB 大小。使用更小的堆栈大小,可以更快地担心。
-
这很奇怪.. 我总是在 MSDN 上看到
char[256]、char[512]、char[1024]和有时char[2048]或char[4096]的堆栈分配。4096实际上在MSDN 的套接字和管道教程/文档。总是这样:#define BUFSIZE 4096:msdn.microsoft.com/en-us/library/windows/desktop/… -
取决于调用堆栈中的其他函数可能已经/将同时消耗多少堆栈,尤其是递归函数。保守的一方最好犯错,这样痛苦会更小。
-
确实,4096 很常见,所以 1 MiB 看起来很不合理。
标签: c++ c++11 memory heap-memory stack-memory