C# Nullable Memory Usage

The C# programming language

You are curious about the memory usage of nullable types in the C# programming language and how the struct used in nullable types affects the memory efficiency of types. Nullable types are specified with a trailing question mark and they allow you to add an additional "null" value to typical value types such as integers.

Example

Initially here, this program runs a test that calculates the memory usage for allocating a large array of nullable integers. You can declare a nullable type array with syntax such as that shown here, using int?[] as the type. This indicates a reference type pointing to a section of memory where many nullable structs are stored together. The GC.GetTotalMemory method is used to determine the resource usage of the program before and after the allocation occurs.

This C# example program determines the memory usage of nullable types.

Program that computes memory usage for nullables [C#]

using System;

class Program
{
    static void Main()
    {
	//
	// Compute the memory usage for a nullable type integer.
	// ... The program allocates one million nullable int structs.
	//
	const int size = 1000000;
	long b1 = GC.GetTotalMemory(true);
	int?[] array1 = new int?[size];
	long b2 = GC.GetTotalMemory(true);
	array1[0] = null;
	Console.WriteLine((b2 - b1) / (double)size);
    }
}

Output

8.000016
Garbage collection visualization

Overview. This program is a complete console application and it measures the memory usage in the managed heap before and after allocating an array of nullable ints. An array of nullable integers is allocated with the int?[] statement. The GC.GetTotalMemory method measures the managed heap in bytes.

GC.GetTotalMemory Usage

Memory usage for nullable integer type. Finally, the program subtracts the final memory usage from the beginning measure usage measurement. The result is that each int? element in the array occupied 8 bytes of storage on the managed heap. If you execute the program with a regular int[] array, you will get 4 bytes per element. This indicates that the nullable type wrapper requires 4 bytes of storage, while the integer itself requires 4 bytes for each element. This is a very efficient implementation for an object type, because in an array many nullable types can be stored in contiguous memory.

Nullable Int Int Array Int Type

Summary

We looked at the memory usage of the nullable type in the C# language, using a console program that performs an experiment and measures the memory in the managed heap. The nullable type elements in an array occupy an additional four bytes over the original variable. This can be useful when researching nullable type efficiency in large programs that must be memory efficient.

.NET Framework Info
.NET