C# Nullable Memory

Question

Nullable types use additional memory. The struct used in nullable types affects memory efficiency. Nullable types are specified with a trailing question mark. They add an additional "null" value to value types such as integers.

Null

Example

Array

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 here, using int?[] as the type.

Int Array

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.

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

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.

Note:The GC.GetTotalMemory method measures the managed heap in bytes. This is found in the System namespace.

GC.GetTotalMemory

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.

Tip:If you execute the program with a regular int array, you will get 4 bytes per element.

Byte type

This indicates 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.

Nullable IntInt

Summary

C# programming language

We looked at the memory usage of the nullable type, using a console program that measures the memory in the managed heap. The nullable type elements in an array occupy an additional four bytes over the original variable.

And:This can be useful when researching nullable type efficiency in large programs that must be memory-efficient.


C#: .NET