dotnet / dotnet/runtime

[Proposal] Prioritize "Scalar Replacement of Aggregates" (SROA) to achieve true Zero-Cost Abstractions

Open
#122,965 9 comments 2 reactions 1 assignee Claimed by @AndyAyersMS View on GitHub
area-CodeGen-coreclr needs-further-triage
Dominant language
C#
Stars
18.3k
Forks
5.6k
PR merge metrics
PR metrics pending

Description

### Description

I have been following the progress on Object Stack Allocation (Issue #11192 and the current roadmap in #104936). While enabling stack allocation for classes is a massive step forward, I would like to propose prioritizing **Scalar Replacement of Aggregates (SROA)** as the ultimate goal for small, non-escaping reference types.

### The Distinction

Currently, the focus seems to be on allocating the object *on the stack* (preserving the object header, method table pointer, etc.).
While this reduces GC pressure, it still incurs:
1. **Header Overhead:** Space taken by the object header/method table.
2. **Indirection:** Accessing fields might still involve pointer arithmetic relative to the stack frame.

**Scalar Replacement (SROA)** goes further by "exploding" the object into its constituent fields (locals/registers) and eliminating the object identity entirely.

### Why Prioritize SROA?

If the JIT can perform Scalar Replacement for reference types (similar to how it handles structs):
1. **True Zero-Cost:** It removes the overhead of the Object Header. A `class` with two `int` fields becomes exactly equal to two `int` local variables.
2. **Register Allocation:** "Exploded" fields are easier for the register allocator to handle compared to fields residing in a stack-allocated memory block.
3. **Modern Idioms:** It perfectly complements modern "fluent" APIs and wrapper types (e.g., `Option`, `Result`, or Builder patterns) where developers prefer classes for API ergonomics but pay a performance penalty.

### Proposal

I suggest that SROA should not just be an "Advanced/Future" optimization (as hinted in #104936 under "Advanced"), but a **core pillar** of the .NET 11 performance roadmap.

Achieving parity between `struct` and `class` for local-scoped data would fundamentally change how we write high-performance C#, removing the need to manually refactor small classes into `structs` or `ref structs` solely for optimization.

**Related Issues:**
Refers to roadmap: #104936

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.