Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get MemoryStream (or another Stream) from Memory<byte> without reallocating?

Is there an existing way get a MemoryStream (or another Stream) from Memory<byte> without reallocating?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading