Search code examples
c#memory-managementjit.net-9.0escape-analysis

With .NET 9 escape analysis, are struct and class now equal?


From a memory allocation point of view structs (in most cases) get allocated on the stack and classes get allocated on the heap. Each having their own tradeoffs. And struct vs class is always included in C# job interviews.

Now with .NET 9 escape analysis, if my understating is correct, this concept is no longer true, and classes will be allocated based on JIT judgement. Am I correct?


Solution

  • Nothing has changed, nor will it change. This is an optimization, currently limited. As Stephen Toub explains in Performance Improvements in .NET 9:

    In .NET 9, object stack allocation starts to happen. Before you get too excited, it’s limited in scope right now, but in the future it’s likely to expand out further.

    and

    ... it’s limited to only handling cases where it can easily prove the object reference doesn’t leave the current frame. Even so, there are plenty of situations where this will help to eliminate allocations, and I expect it’ll be expanded to handle more and more cases in the future. When the JIT does choose to allocate an object on the stack, it effectively promotes the fields of the object to be individual variables in the stack frame.

    Even on later versions this won't change the difference between value and reference types. It won't start producing defensive copies or value equality in reference types, nor would it allow allocating a large list or buffer on the stack, or force copying when passing an object to a method.