I am trying to understand the object size difference between 32 bit and 64 bit processors. Let’s say I have a simple class
class MyClass
{
int x;
Objects have some overhead beyond the member variables. In 32-bit implementations of .NET, the allocation overhead appears to be 12 bytes. As I recall, it's 16 bytes in the 64 bit runtime.
In addition, object allocations are aligned on the next 8 byte boundary.
The CLR is free to lay out objects in memory as it sees fit. It's an implementation detail. You should not rely on any specific layout.
The difference you see is due to the missing TypeHandle field which is also a part of the CLR object header. Additionally, the fields may be aligned to byte boundaries.
From Advanced .Net Debugging - CLR Object’s Internal Structure:
An object’s CLR internal structure is:
[DWORD: SyncBlock][DWORD: MethodTable Pointer][DWORD: Reference type pointer]…[Value of Value Type field]…
Object Header: [DWORD: SyncBlock]
Object Pointer: [DWORD: MethodTable Pointer][DWORD: Reference type pointer]…[Value of Value Type field]…Every Object is preceded by an ObjHeader (at a negative offset). The ObjHeader has an index to a SyncBlock.
So your object is likely laid out like this:
x86: (aligned to 8 bytes)
Syncblk TypeHandle X Y ------------,------------|------------,------------| 8 16
x64: (aligned to 8 bytes)
Syncblk TypeHandle X Y -------------------------|-------------------------|------------,------------| 8 16 24
See also: Drill Into .NET Framework Internals to See How the CLR Creates Runtime Objects
Seems to me, any object should have some kind of pointer to its class. That'd account for your extra 4 or 8 bytes.
The layout of an object is really an implementation thing, though. If you care about the layout, there are attributes designed to explicitly tell .net where and how you want the members positioned. Check out StructLayoutAttribute.
The sync block sits at a negative offset from the object pointer. The first field at offset 0 is the method table pointer, 8 bytes on x64. So on x86 it is SB + MT + X + Y = 4 + 4 + 4 + 4 = 16 bytes. The sync block index is still 4 bytes in x64. But the object header also participates in the garbage collected heap, acting as a node in a linked list after it is released. That requires a back and a forward pointer, each 8 bytes in x64, thus requiring 8 bytes before the object pointer. 8 + 8 + 4 + 4 = 24 bytes.