params arrays create heap allocation on every call. C# 13 allows params with Span for zero-allocation variable args.
Old Way (Allocates):
// params creates new int[] on every call
public int Sum(params int[] numbers)
{
return numbers.Sum();
}
// Called 1 million times = 1 million array allocations!
Sum(1, 2, 3);
New Way – C# 13 (Zero Allocation):
// params with ReadOnlySpan = stack allocation public int Sum(params ReadOnlySpannumbers) { int total = 0; foreach (var n in numbers) total += n; return total; } // Called 1 million times = 0 heap allocations! Sum(1, 2, 3); // Stored on stack, not heap
Benchmark:
params int[]: 1M calls = 1M allocations = 120ms params ReadOnlySpan: 1M calls = 0 allocations = 30ms = 4x faster!
Available in C# 13 (.NET 9+)
