Reputation: 3045
In subtopic Storage Overhead (on Chapter) -C# 5.0 in a Nutshell book- there is this general note that says:
Now, I'm wondering why the fields in struct A generates a waste of space? Or, what is the author's point with the entire note?
Upvotes: 5
Views: 417
Reputation: 109587
There are two reasons for this default for structs:
1) Performance, as others have already explained. Placing the field members at multiples of their size allows faster transfers.
2) To be the same as the default for most C/C++ compilers. This makes interop with C/C++ (including all the Windows API) a bit easier.
Note that if you don't need to marshal your structures, you can use [StructLayout(LayoutKind.Auto)]
:
[StructLayout(LayoutKind.Auto)]
struct A
{
byte b;
long l;
}
With that, the following code
unsafe
{
Console.WriteLine(sizeof(A));
}
prints 12
, which indicates better packing.
If you use [StructLayout(LayoutKind.Sequential, Pack = 1)]
you can get the size down to 9
.
Upvotes: 4
Reputation: 5722
They are generally aligned at processor word boundaries, so that retrieving them is a simple one-cycle operation. Otherwise, the CLR would have to pick up the whole address, and XOR/shift the struct field to reference it.
Upvotes: 2
Reputation: 54887
Each byte
field occupies 1 byte, whilst each long
field occupies 8 bytes. This means that, whilst b
could be placed anywhere in memory, l
needs to be placed at an address that is a multiple of 8. It cannot be placed at address 0
since that is already occupied by b
; thus, it must be placed at the next available multiple of 8, which is 8
, causing the 7 bytes of intervening space to be wasted.
---------------------------------------------------------------------------------
| 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 |
---------------------------------------------------------------------------------
<--b-> <------------------l-------------------->
<--------------waste------------->
Upvotes: 9
Reputation: 526
Just look at the alignment. A Long must be at position 0, 8, 16,...
But if we have first the byte it looks like that:
b-------llllllll
With b beeing the byte b and l beeing the long l. The - are the "wasted space" So as you can see the struct uses a whole 16 bytes but only 9 bytes are used thus 7 bytes are wasted
Upvotes: 5