What is the memory footprint of a Nullable<T>

Viewed 7009

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?

8 Answers

The .NET (and most other languages/frameworks) default behavior is to align struct fields to a multiple of their size and structs themselves to a multiple of the size of their largest field. Reference: StructLayout

Nullable<T> has a bool flag and the T value. Since bool takes just 1 byte, the size of the largest field is the size of T; and Nullable doubles the space needed compared to a T alone. Reference:Nullable Source

Clarification: If T is itself a non-primitive struct rather than a primitive type, Nullable increases the space needed by the size of the largest primitive field within T or, recursively, within any of T's non-primitive fields. So, the size of a Nullable<Nullable<bool>> is 3, not 4.

You can check using some code similar to the one at https://www.dotnetperls.com/nullable-memory.

I got the following results:

  • Int32 4 bytes
  • Int32? 8 bytes
  • Int16 2 bytes
  • Int16? 4 bytes
  • Int64 8 bytes
  • Int64? 16 bytes
  • Byte 1 bytes
  • Byte? 2 bytes
  • bool 1 bytes
  • bool? 2 bytes

32-bit and 64-bit machines:

  • int == 4 bytes
  • int? == 8 bytes == 4 for int + 4 for the nullable type wrapper.

The nullable type wrapper requires 4 bytes of storage. And the integer itself requires 4 bytes for each element. This is an efficient implementation. In an array many nullable types are stored in contiguous memory.

Based on a personal test (.NET Framework 4.6.1, x64, Release) and from – https://www.dotnetperls.com/nullable-memory

Also, if interesting: why int on x64 equals only 4 bytes?

Note: this is valid for Nullable<int> only, the size of Nullable<T> totally depends on the type.

Related