This is where it all started. I faced an interesting problem while working on my Sessions application. Declaring a structure as :
Struct ShortIntIf someone is asked about the size of this structure. I bet most people would answer it as I did : 6 bytes.
But surprisingly, the answer is 8 bytes.
Simple reason for that being the memory is allocated in the chunks and if the declaration of structure is done wisely, it could save a lot of memory:
Struct exampleStructHere if we look at this structure, the memory for this block is allocated as follows:
Byte b1 ----- A chunk of 4 bytes is allocated
Int32 i ------ This chunk has only 3 bytes left so a new chunk of 4 bytes alloted
short s ------ Previous chunk is full. So next 4 byte chunk is alloted.
Byte b2 ----- Previous chunk has 2 bytes left and can accomodate a byte. Hence the byte variable is accomodated in teh same chunk.
So total size becomes 12 bytes.
Now if we redefine our structure as follows:
StructNow the memory allocation would be as follows:
Byte b1 ----- A chunk of 4 bytes is alloted
Byte b2 ----- A byte in teh same chunk
short s ------ Previous chunk has 2 bytes left in it
Int32 i ----- Since the previous chunk is full, a new chunk is alloted
Hense the total size is 8 bytes only.
More could be found on the following links :