这是我在 Windows 7 下的 MSVC++ 2010 上做的一个简单测试:
// A struct with sizeof(s) == 4, e.g 4 bytes
struct s
{
int x;
};
// Allocate 1 million structs
s* test1 = new s[1000000];
// Memory usage show that the increase in memory is roughly 4 bytes * 1000000 - As expected
// NOW! If I run this:
for (int i = 0; i < 1000000; i++)
new s();
// The memory usage is disproportionately large. When divided by 1000000, indicates 64 bytes per s!!!
这是常识还是我遗漏了什么?之前我总是在需要时动态创建对象。例如,网格中每个三角形的 new Triangle() 等。
单个实例的动态内存分配确实存在数量级的开销吗?
干杯
编辑:
刚刚在 Windows XP 上使用 g++ 编译并运行相同的程序:现在开销是 16 个字节,而不是之前观察到的 64 个字节!很有意思。