Parsa99
Parsa99

Reputation: 496

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?

Upvotes: 0

Views: 258

Answers (2)

Andy Ayers
Andy Ayers

Reputation: 1132

This optimization works for more than just boxing, though as others have noted it doesn't kick in all that often, yet. Think of it as a first step. We have already made enhancements to this in .NET 10 and have more in the works. For example we just merged changes to allow small known-sized arrays of non-GC types to be stack allocated.

Unlike say Java, the .NET 9 JIT will put objects on the stack and then not "promote" their fields to variables; whether promotion happens or not is a separate optimization (though one we hope happens most of the time).

Upvotes: 1

Panagiotis Kanavos
Panagiotis Kanavos

Reputation: 131591

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.

Upvotes: 2

Related Questions