What is the memory overhead of a .NET custom struct type?

后端 未结 4 1547
春和景丽
春和景丽 2021-02-20 05:27

There is a fixed overhead associated with a .NET object as more fully outlined in this SO question: What is the memory overhead of a .NET Object being 12 or 24 bytes depending o

4条回答
  •  名媛妹妹
    2021-02-20 06:02

    Where does that leave custom struct types that you put together in your application?

    They are no different than primitive types. They carry no additional overhead other than the fields they have. The fact that they derive from object doesn't mean they incur the overhead that reference types carry, which is the method table pointer and sync root block.

    You can test this out using Marshal.SizeOf:

    void Main()
    {
        var f = new Foo();
        Console.WriteLine(Marshal.SizeOf(f));
    }
    
    public struct Foo
    {
        public int X { get; set; }
        public int Y { get; set; }
    }
    

    This will print 8 in a 32bit mode, which is exactly two integer values (4 bytes each).

    Note Marshal.SizeOf will output the size of the unmanaged object. The CLR is still free to re-order fields or pack them together.

提交回复
热议问题