Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the memory footprint of a Nullable<T>

Tags:

An int (Int32) has a memory footprint of 4 bytes. But what is the memory footprint of:

int? i = null; 

and :

int? i = 3; 

Is this in general or type dependent?

like image 241
PVitt Avatar asked Sep 04 '09 20:09

PVitt


People also ask

What is a nullable data type?

Nullable types are a feature of some programming languages which allow a value to be set to the special value NULL instead of the usual possible values of the data type.

What is a nullable value?

You typically use a nullable value type when you need to represent the undefined value of an underlying value type. For example, a Boolean, or bool , variable can only be either true or false . However, in some applications a variable value can be undefined or missing.

What is a nullable reference type?

Nullable reference types are a compile time feature. That means it's possible for callers to ignore warnings, intentionally use null as an argument to a method expecting a non nullable reference. Library authors should include runtime checks against null argument values.

What is null and nullable?

Technically a null value is a reference (called a pointer in some languages) to an empty area of memory. Reference variables (variables that contain an address for data rather than the data itself) are always nullable , which means they are automatically capable of having a null value.


2 Answers

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.

like image 90
Charles Bretana Avatar answered Nov 12 '22 10:11

Charles Bretana


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.

like image 31
JaredPar Avatar answered Nov 12 '22 09:11

JaredPar