Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why storage overhead generates waste in C# data types?

Tags:

c#

.net

In subtopic Storage Overhead (on Chapter) -C# 5.0 in a Nutshell book- there is this general note that says:

enter image description here

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?

like image 478
InfZero Avatar asked Jul 06 '13 15:07

InfZero


2 Answers

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------------->
like image 148
Douglas Avatar answered Sep 19 '22 15:09

Douglas


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

like image 38
Lukas Häfliger Avatar answered Sep 17 '22 15:09

Lukas Häfliger