Why does a reference type occupies 8 bytes in memory?
I assume that 4 bytes are needed to identify the object's type (or for the
virtual table), but what about the remaining 4 bytes?
Second, why does the size of a structure that has only one byte in it, is
rounded to 4?
Jon Shemitz - 09 Apr 2006 19:35 GMT
> Why does a reference type occupies 8 bytes in memory?
> I assume that 4 bytes are needed to identify the object's type (or for the
> virtual table), but what about the remaining 4 bytes?
Every reference type can be locked - the 'other' four bytes are a
SyncBlockIndex, an index into a table of sync blocks. This consumes a
modest amount of memory, and allows us to lock our actual data,
instead of having to create explicit critical section objects.
> Second, why does the size of a structure that has only one byte in it, is
> rounded to 4?
Modern CPUs read aligned data much faster than unaligned data.

Signature
<http://www.midnightbeach.com> Contracting, consulting, training
.NET 2.0 for Delphi Programmers <http://www.midnightbeach.com/.net>
In production - in stores by June
Willy Denoyette [MVP] - 09 Apr 2006 22:34 GMT
| Why does a reference type occupies 8 bytes in memory?
| I assume that 4 bytes are needed to identify the object's type (or for the
| virtual table), but what about the remaining 4 bytes?
| Second, why does the size of a structure that has only one byte in it, is
| rounded to 4?
I don't know where you did get this size info from, but actually a reference
instance will occupy at least 12 bytes on the managed heap.
For instance the following class:
class C{}
will occupy 12 bytes on the managed heap:
int synch# ;the synch. block index (some houskeeping bits and the actual
block #).
int MT ; the Method table pointer
Int32 ; dummy
just like:
class C {
int byte;
}
or:
class C {
int i;
}
A value type (a structure) with only a single byte in it will occupy 4 bytes
on the stack and 12 bytes (see above) when boxed), just like a struct of 4
bytes or a struct with a single int.
That means that both:
public struct st1
{
public byte b;
}
and:
public struct st2
{
public byte b;
public byte b2;
public byte b3;
public byte b4;
}
occupy 4 bytes on the stack.
Willy.