Skip to content
Tutorials Center
My learning

Topics

C# Reference ยท .NET, Tools and Concepts

Memory management in C#

How C# programs use memory: the stack and the managed heap, value and reference types, boxing, stackalloc, Span<T>, and how to measure and reduce allocations.

A running .NET program uses several kinds of memory. The stack holds method frames: parameters, local variables and return addresses. It is fast and cleaned up automatically when a method returns. The managed heap holds objects created with new (classes, arrays, strings, delegates, boxed values), and the garbage collector reclaims it. Unmanaged memory is anything outside the GC's control: native libraries, file handles, memory from NativeMemory.

Understanding where data lives explains many C# behaviors: why copying a struct copies its data while copying a class variable copies a reference, why boxing is expensive, and why Span<T> and stackalloc exist.

C#
int x = 5;                       // value on the stack
var list = new List<int>();      // reference on the stack, object on the heap
object boxed = x;                // allocates a heap copy of the int
Span<int> temp = stackalloc int[16]; // 64 bytes on the stack, no GC involved

Try it

C# Value copy versus reference copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

C# Measuring allocations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Concepts

Stack and heap

Value types (int, double, bool, structs, enums) are stored inline in whatever contains them: on the stack for a local variable, inside the object for a field, inside the array for array elements. Reference types are stored on the heap, and variables hold a reference. Contrary to a popular summary, "value types live on the stack" is not a rule: a struct field of a class lives on the heap with that object.

Compare:

Aspect Stack Heap
Allocation cost A pointer move A pointer move plus later GC work
Lifetime Until the method returns Until the object is unreachable
Size Small (about 1 MB per thread by default on many systems) Limited by memory
Cleanup Automatic Garbage collector

Boxing

Converting a value type to object or to an interface it implements creates a heap object that holds a copy. Unboxing copies the value back and checks the type. Boxing in hot loops, for example by using a non-generic collection, formatting values through object, or using a struct as an interface variable, allocates for each iteration. Generics (List<int>) avoid it. See Boxing.

stackalloc and Span

stackalloc reserves a block on the stack that disappears when the method returns. In safe code it must be assigned to a Span<T> or ReadOnlySpan<T>. Span<T> is a window over contiguous memory, on the stack, in an array or in unmanaged memory, and is itself a ref struct, which means it can never end up on the heap. Use small, bounded sizes with stackalloc (a few hundred bytes to a few kilobytes), because a stack overflow cannot be caught. See Span.

Reducing allocations

  • Prefer structs for small, short-lived, immutable data, but not for large ones: copying costs more than a reference.
  • Reuse buffers with ArrayPool<T>.Shared and StringBuilder.
  • Use Span<T>, ReadOnlySpan<char> and string.Create for slicing and parsing without creating substrings.
  • Avoid capturing lambdas in hot paths; mark them static to guarantee they capture nothing.
  • Dispose unmanaged resources promptly (using).

Usage notes

  • Measure with GC.GetAllocatedBytesForCurrentThread() around code that runs on the current thread. It is precise for small tests; use BenchmarkDotNet with the memory diagnoser for real analysis.
  • Strings are immutable heap objects. Every concatenation creates a new string; a loop over += is quadratic in time and memory.
  • Closures allocate. A lambda that captures a local variable allocates a closure object (and a delegate each time it is converted).
  • Large objects are special. Objects of 85,000 bytes or more go to the large object heap, which is collected only with generation 2.
  • Stack size is fixed. Deep recursion or large stackalloc blocks can end the process with a StackOverflowException, which cannot be caught.
  • ref locals and ref structs let you refer to existing memory without copying it, but they cannot be stored in fields of ordinary classes.
  • Exact byte counts vary by runtime version, architecture and optimization settings, so tests should compare (zero or more than zero) rather than hard-code sizes.