C# 13 `params ReadOnlySpan<T>` Zero-Allocation Parameter Arrays
1Concept
Prior to C# 13, `params T[]` allocated a new heap array on every method invocation. C# 13 introduces `params ReadOnlySpan<T>`, allocating the arguments directly on the caller's stack with zero GC heap allocations.
2Architecture Diagram
Legacy params int[] (C# 12 and older): Invocation ──> Allocates `new int[3]` on Managed Heap ──> GC Garbage Created Modern params ReadOnlySpan<int> (C# 13): Invocation ──> Emits stackalloc buffer on Thread Stack ──> ZERO Heap Allocation!
3Code Example
C# 13 & .NET 9
using System;
public class ParamsSpanDemo
{
// C# 13 params ReadOnlySpan<T>
public static int SumAll(params ReadOnlySpan<int> numbers)
{
int sum = 0;
foreach (int n in numbers)
{
sum += n;
}
return sum;
}
public static void Main()
{
// Stack allocated arguments!
int total = SumAll(10, 20, 30, 40, 50);
Console.WriteLine($"Zero-Heap-Allocation Sum: {total}");
}
}4Expected Output
Zero-Heap-Allocation Sum: 150
5Key Takeaways
- ✓`params ReadOnlySpan<T>` completely eliminates GC pressure from variable-argument methods.
- ✓RyuJIT vectorizes Span loops using SIMD (AVX2/AVX-512) automatically.
- ✓Can accept both inline arguments `SumAll(1, 2)` and existing arrays `SumAll(arr)` seamlessly.