我试图使用以下代码确定.NET数组(在32位进程中)标头的开销:
long bytes1 = GC.GetTotalMemory(false);
object[] array = new object[10000];
for (int i = 0; i < 10000; i++)
array[i] = new int[1];
long bytes2 = GC.GetTotalMemory(false);
array[0] = null; // ensure no garbage collection before this point
Console.WriteLine(bytes2 - bytes1);
// Calculate array overhead in bytes by subtracting the size of
// the array elements (40000 for object[10000] and 4 for each
// array), and dividing by the number of arrays (10001)
Console.WriteLine("Array overhead: {0:0.000}",
((double)(bytes2 - bytes1) - 40000) / 10001 - 4);
Console.Write("Press any key to continue...");
Console.ReadKey();
结果是
204800
Array overhead: 12.478
在32位进程中,object [1]的大小应与int [1]相同,但是实际上开销跳升了3.28个字节,
237568
Array overhead: 15.755
有人知道为什么吗?
(顺便说一句,如果有人好奇的话,非数组对象(例如,上面循环中的(object)i)的开销约为8个字节(8.384)。我听说在64位进程中为16个字节。)
神不在的星期二
达令说