⚙️ C# / .NET Intermediate

What are memory-related performance features in modern C#?

Answer

Modern C# provides several features to avoid unnecessary heap allocations. Span<T>: a stack-allocated view over a contiguous region of memory (array, stack-allocated memory, or unmanaged). No heap allocation — zero-copy slicing: ReadOnlySpan<char> slice = "Hello World".AsSpan(0, 5);. Cannot be stored in fields (stack-only). Memory<T>: like Span but can be stored and used asynchronously (heap-based). ArrayPool<T>: rent and return array buffers to avoid GC pressure: var arr = ArrayPool<int>.Shared.Rent(100); try { ... } finally { ArrayPool<int>.Shared.Return(arr); }. stackalloc: allocate arrays on the stack (C# 7.3+, usable with Span): Span<int> buffer = stackalloc int[128];. ref structs: stack-only structs (cannot be boxed or stored on heap). String interpolation handlers (C# 10+): avoid intermediate strings. These features power ASP.NET Core's high throughput.