数组的内存大小是多少? [英] Which size does an array have in memory?
问题描述
我想知道数组的大小。我想到了 size * sizeof(item)+ sizeof(pointer)
,但是分配了多少字节才能引用该数组?
< div类= h2_lin>解决方案
以字节为单位的数组开销为:
值类型数组|引用类型数组
x86 12 16
x64 24 32
您可以计算这些使用系统的
的值;
class Test
{
const int Size = 100000;
static void Main()
{
Console.WriteLine(以{0}位运行,IntPtr.Size * 8);
Tester< string>();
Tester< double>();
Console.ReadKey();
}
static void Tester< T>()
{
var array = new object [Size];
long initialMemory = GC.GetTotalMemory(true);
for(int i = 0; i< Size; i ++)
{
array [i] = new T [0];
}
long finalMemory = GC.GetTotalMemory(true);
GC.KeepAlive(array);
总计= finalMemory-initialMemory;
Console.WriteLine(每个{0} []的大小:{1:0.000}字节,typeof(T)。名称,
((总计)/大小) ;
}
}
此代码是此处代码的修改版本 .NET阵列的开销?
显然,您必须以32位和64位执行它。
为此,您必须添加:数组的元素(因此 size * sizeof(element)
)加上至少一个对您需要的数组的引用(因此 IntPtr.Size
)。
请注意,我注意到了一些不一致之处。如果我创建 double [1]
,那么单个double的数组,每个数组在8字节边界上都完全对齐,但所用空间似乎只有20字节/数组(32位,所以12 + sizeof(double))。这显然是不可能的,因为20不能被8整除。我认为 GC.GetTotalMemory
正在忽略对象之间的空缺。这可能是某些字节/数组的额外开销(取决于数组元素的类型)。对于 byte [1]
,中等大小是16个字节/数组(32位,所以12 + sizeof(byte)+ 3)。这似乎更正确。
I wonder which size an array has. I thought of size * sizeof(item) + sizeof(pointer)
but how many bytes are allocated for being able to reference the array?
The overhead of arrays in bytes are:
Architecture | Value Type Array | Reference Type Array
x86 12 16
x64 24 32
You can calc these values with
using System;
class Test
{
const int Size = 100000;
static void Main()
{
Console.WriteLine("Running at {0} bits", IntPtr.Size * 8);
Tester<string>();
Tester<double>();
Console.ReadKey();
}
static void Tester<T>()
{
var array = new object[Size];
long initialMemory = GC.GetTotalMemory(true);
for (int i = 0; i < Size; i++)
{
array[i] = new T[0];
}
long finalMemory = GC.GetTotalMemory(true);
GC.KeepAlive(array);
long total = finalMemory - initialMemory;
Console.WriteLine("Size of each {0}[]: {1:0.000} bytes", typeof(T).Name,
((double)total) / Size);
}
}
This code is a modified version of the one from here Overhead of a .NET array?
Clearly you have to execute it at 32 and at 64 bits.
To this overhead you have to add: the elements of the array (so size * sizeof(element)
) plus at least a reference to the array that you'll need to have (so IntPtr.Size
).
Note that there are some inconsistencies I've noticed. If I create double[1]
, so arrays of a single double, each one of them is perfectly aligned on the 8 byte boundary, but the space used seems to be only 20 bytes/array (at 32 bits, so 12 + sizeof(double)). This is clearly impossible, because 20 isn't divisible by 8. I think the GC.GetTotalMemory
is "ignoring" the hole between objects. This could be an additional overhead of some bytes/array (depending on the type of elements of the array). For byte[1]
the medium size is 16 bytes/array (at 32 bits, so 12 + sizeof(byte) + 3). This seems to be more correct.
这篇关于数组的内存大小是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!