Using `ReadOnlySpan<byte>` properties instead of `static readonly byte[]` fields can eliminate heap allocations entirely — even on .NET Framework — because the compiler embeds the data directly into the assembly metadata. The optimization works only for byte-sized primitives (byte, sbyte, bool) with constant values, and only when returning `ReadOnlySpan<T>` (not `Span<T>`). For other types like `int[]`, the zero-allocation path requires .NET 7+ via `RuntimeHelpers.CreateSpan`. The post walks through the generated IL to confirm the behavior, highlights dangerous edge cases (non-constant values, mutable Span<T>) that silently cause per-access allocations, and notes that collection expressions provide partial compile-time safety for static properties but not local variables.
Table of contents
Span<T> and ReadOnlySpan<T> are a performance mainstay for .NETRemoving byte[] allocations with ReadOnlySpan<byte>What's happening behind the scenes?Be careful, things can go wrong…Conclusion1 Comment
Sort: