我知道这个问题已有 4 年历史了,但公认的答案毫无意义(正如贾斯汀·雷蒙德指出的那样)。
Nick Babcock 的方法并不精确,因为元素数量太少;堆上总是有一些开销,您也将对其进行测量。
为了展示这一点,我使用了更大的数据类型和更多元素(4096):
在g++ 6.2.1
and linux x64
sizeof(void*) = 8
and sizeof (bigDataType_t) = 800
(bigData_t
is long[100]
).
那么我们期待什么呢?每种类型的列表都必须在堆上存储实际数据;std::list
每个链接存储 2 个指针(向后和向前),std::forward_list
只有一个(前进)。
预期内存std::list
:
4096 x 800 + 2 x 8 x 4096 = 3,342,336 bytes
实际内存为std::list
: 3,415,040 bytes
预期内存std::forward_list
:
4096 x 800 + 1 x 8 x 4096 = 3,309,568 bytes
实际内存为std::forward_list
: 3,382,272 bytes
I used Massif http://valgrind.org/docs/manual/ms-manual.html获取程序的堆使用情况。
正如我们所看到的,这些数字非常吻合。当使用大数据类型时,额外指针的内存没有太大区别!
使用时char
作为数据类型(作为OP),预期的内存占用和实际的内存占用不太吻合,很可能是因为一些开销。但是,内存消耗没有因素 3。
std::list: Expected 69,632 bytes, actual: 171,008 bytes
std::forward_list: Expected 36,864 bytes, actual: 138,240 bytes
My code:
#include <list>
#include <forward_list>
struct bigData_t {
long foo[100];
};
typedef bigData_t myType_t;
// typedef char myType_t;
int main()
{
#ifdef USE_FORWARD_LIST
std::forward_list<myType_t> linkedList;
#else
std::list<myType_t> linkedList;
#endif
for (int i = 0; i < 4096; i++) {
myType_t bigData;
linkedList.push_front(bigData);
}
return 0;
}