对象占用多少内存?

时间:2018-02-02 10:24:48

标签: c# .net-core

我做了一些测试并且非常惊讶......编译模式x64。第一次测试显示4个字节,这里一切都很好。第二个32.哇,我想。并且第三次得分32 WTF ???

static int count = 10000000;

    static void Array_1()
{
    var size = GC.GetTotalMemory(true);
    var arr = new int[count];

    for (var i = 0; i < count; ++i)
    {
        arr[i] = i;
    }

    var mem = GC.GetTotalMemory(true) - size;

    Console.WriteLine("Allocated memory: " + mem + ", per item: " + Math.Truncate((double)mem / count) + ", anti optimize " + arr.Last());
}

static void Array_2()
{
    var size = GC.GetTotalMemory(true);
    var arr = new object[count];

    for (var i = 0; i < count; ++i)
    {
        arr[i] = new object();
    }

    var mem = GC.GetTotalMemory(true) - size;

    Console.WriteLine("Allocated memory: " + mem + ", per item: " + Math.Truncate((double)mem / count) + ", anti optimize " + arr.Last().GetHashCode());
}

static void Array_3()
{
    var size = GC.GetTotalMemory(true);
    var arr = new C[count];

    for (var i = 0; i < count; ++i)
    {
        arr[i] = new C { Val0 = i, Val1 = i };
    }

    var mem = GC.GetTotalMemory(false) - size;

    Console.WriteLine("Allocated memory: " + mem + ", per item: " + Math.Truncate((double)mem / count) + ", anti optimize " + arr.Last().Val0 + arr.Last().Val1);
}

[StructLayout(LayoutKind.Sequential, Pack = 1)]
class C
{
    public int Val0;
    public int Val1;
}

我的问题甚至不是为什么在第二次测试中一个实例占用32个字节。但是为什么在第三次测试中实例不需要40个字节。

0 个答案:

没有答案