
Stack vs Heap Is the Wrong Question: What Really Separates Value and Reference Types
- كاتب موثّق
- .NET 10
محتويات المقال
OrderLine class into a record struct because "structs live on the stack, so this takes load off the GC." A week later, support reports that coupon discounts stopped applying, though nobody touched the discount code. The culprit is a loop that reads var line = lines[i] and lowers line.Price. With a class, line pointed at the item in the list; with a struct, it's a copy, so the loop discounts copies and throws them away. And the lines never moved to the stack: they sit in the internal array of the List<OrderLine>, on the heap.
The common misconception
int, DateTime, your structs) live on the stack, reference types (classes, arrays, strings) live on the heap, and that's what makes them different. It's in countless tutorials and interview answers, and Microsoft's own docs described value types that way for years.
int in an ordinary method really does live in the method's stack frame, or in a CPU register, and vanishes when the method returns. Boxing is usually drawn as a value being copied from the stack to the heap, which reinforces the picture. And developers coming from C++ are used to choosing stack or heap themselves.
What actually happens
The real difference: what a variable holds
List<string>, both copies share that list.
Storage follows the variable, not the type
public readonly record struct Point(int X, int Y);public class Route{ public Point Start { get; set; } // part of every Route object's memory public Point[] Stops { get; } = new Point[16]; // 16 Points stored inline in one heap array public int Demo() { var a = new Point(1, 2); // ordinary local: stack frame or CPU registers object boxed = a; // boxing: copies a into a new object, normally on the heap var b = new Point(3, 4); // captured by the lambda below: b lives in a closure object Func<int> shiftX = () => b.X + 1; return a.X + shiftX() + Start.X + Stops.Length + boxed.GetHashCode(); } public async Task<int> LaterAsync(Task signal) { var c = new Point(5, 6); // still needed after the await, so it becomes a field await signal; // of the async state machine, which is copied to the return c.X; // heap if the method really has to wait }}Fields: Startisn't on any stack. Its 8 bytes are part of theRouteobject, which normally lives on the heap.Array elements: an array of structs stores the values themselves, side by side, inside the array object. List<T>keeps its items in an array, so theOrderLinedata stayed on the heap.Captured locals: the compiler turns binto a field of a hidden class, and in .NET 10 that closure object is still allocated on the heap.Async methods: locals that must survive an awaitbecome fields of a compiler-generated state machine. In Release builds it stays on the stack if every awaited task has already finished, and is copied to the heap if the method has to wait.Boxing: converting a value to objector to an interface copies it into a new object. Changingalater doesn't changeboxed.
a matches the folklore, and even a may never touch memory: with an optimization called physical promotion, the JIT can keep a struct's fields in CPU registers.
Reference types don't always live on the heap either
The bug that really matters: copies
var lines = new List<OrderLine> { new("SKU-1", 100m), new("SKU-2", 40m) };for (var i = 0; i < lines.Count; i++){ var line = lines[i]; // a copy of the struct, not the item inside the list line.Price -= 10m; // discounts the copy}Console.WriteLine(lines[0].Price); // 100: the discount was silently lostpublic record struct OrderLine(string Sku, decimal Price);var lines = new List<OrderLine> { new("SKU-1", 100m), new("SKU-2", 40m) };for (var i = 0; i < lines.Count; i++){ var line = lines[i]; lines[i] = line with { Price = line.Price - 10m }; // store the new value back}Console.WriteLine(lines[0].Price); // 90public readonly record struct OrderLine(string Sku, decimal Price);readonly. The loop stops fighting the copy: it builds a new value with with and stores it back in the list. And if OrderLine is something you want to update in place and share, it was a reference type all along, and going back to a class is a perfectly good fix.
Myth vs reality
List<T> live in its heap array, and each boxing creates a new object | |
How to apply it in your project
Choose by meaning first Is the type a value, like an amount, a coordinate or a date range, or a thing with an identity that changes over time, like an order? Things with identity should be classes. Keep structs small and immutable Microsoft's design guidelines suggest a struct only for a single, immutable value under 16 bytes that won't be boxed often. Mark it readonlyso the compiler enforces the immutability.Hunt for lost copies Look for code that reads a struct from a list, dictionary or array, changes it, and never writes it back. In hot paths, also look for structs passed as objector as an interface: each one is a box.Measure before you claim a win Prove performance changes with a benchmark that reports allocations, such as BenchmarkDotNet's [MemoryDiagnoser]. The JIT may already remove the allocation you want to save, or your change may add boxes elsewhere.
Key takeaways
Value versus reference is about what a variable holds and what gets copied, not where memory is allocated. A struct lives wherever its variable lives, which often means inside a heap object, array, closure or state machine. The JIT is free to move things: in .NET 10 it can stack-allocate some non-escaping objects and keep struct fields in registers. Most struct bugs are lost updates on copies; readonlystructs turn them into compile errors.Pick structorclassby semantics, and claim a performance win only after measuring it.
📚 المصادر
Value types (C# reference) — Microsoft Learn Boxing and Unboxing (C# programming guide) — Microsoft Learn Choosing Between Class and Struct (Framework Design Guidelines) — Microsoft Learn What's new in .NET 10 runtime: stack allocation and escape analysis — Microsoft Learn The Stack Is An Implementation Detail, Part One — Eric Lippert (Microsoft Learn archive)
التعليقات (0)