What is the memory footprint of a Nullable<T>
I'm not 100% sure, but I believe it should be 8 Bytes, 4 bytes for the int32, and (since every thing has to be 4-Byte aligned on a 32 bit machine) another 4 bytes for a boolean indicating whether the integer value has been specified or not.
Note, thanks to @sensorSmith, I am now aware that newer releases of .Net allow nullable values to be stored in smaller footprints (when the hardware memory design allows smaller chunks of memory to be independently allocated). On a 64 Bit machine it would still be 8 bytes (64 bits) since that is the smallest chunk of memory that can be addressed...
A nullable for example only requires a single bit for the boolean, and another single bit for the IsNull flag and so the total storage requirements is less than a byte it theoretically could be stored in a single byte, however, as usual, if the smallest chunk of memory that can be allocated is 8 bytes (like on a 64 bit machine), then it will still take 8 bytes of memory.
The size of Nullable<T>
is definitely type dependent. The structure has two members
- boolean: For the hasValue
- value: for the underlying value
The size of the structure will typically map out to 4 plus the size of the type parameter T.
int? a = 3; 00000038 lea ecx,[ebp-48h] 0000003b mov edx,3 00000040 call 78BFD740 00000045 nop a = null; 00000046 lea edi,[ebp-48h] 00000049 pxor xmm0,xmm0 0000004d movq mmword ptr [edi],xmm0
It seems that first dword is for the value, and the second one is for null flag. So, 8 bytes total.
Curious, BinaryWritter doesn't like to write nullable types. I was wandering if it could pack it tighter then 8 bytes...