Is there an existing way get a MemoryStream (or another Stream) from Memory<byte> without reallocating?
>Solution :
When you construct a MemoryStream from a byte[] the array is assigned as the stream’s buffer. In this case there is no additional allocation or copy.
Unfortunately there’s no constructor that takes Memory<byte>. You’ll have to call Memory<byte>.ToArray() to get there, and that does allocate. The documentation comment for Memory<T>.ToArray() states:
Copies the contents from the memory into a new array. This heap allocates, so should generally be avoided, however it is sometimes necessary to bridge the gap with APIs written in terms of arrays.
(Internally this is implemented via Span<T>.ToArray().)
The Microsoft.Toolkit.HighPerformance package adds an AsStream() extension that creates a thin stream wrapper around Memory<byte>, allowing you to read/write to your Memory<byte> without allocations.