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?
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------------->
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With