Wednesday, October 17, 2007

Why is a Short of 4 bytes

Why is a Short of 4 bytes

This is where it all started. I faced an interesting problem while working on my Sessions application. Declaring a structure as :
Struct ShortInt
{
Short firstShort;
Int32 secondInt;
}

If 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:

Taking example:

Struct exampleStruct
{
Byte b1;
Int32 i;
short s;
Byte b2;
}

Here 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:

Struct
exampleStruct
{
Byte b1;
Byte b2;

short s;
Int32 i;
}

Now 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 :

http://www.vsj.co.uk/articles/display.asp?id=501
http://msdn.microsoft.com/msdnmag/issues/05/01/MemoryOptimization/default.aspx



--Ashutosh