Is there a MemoryStream that accepts a Span<T> or Memory<T>?

Viewed 3349

I'm reading data from many sources (MemoryMappedFiles or FileStream). One problem is though that every single call to read a byte, int or some other type is extremely slow. So I'd like to read a chunk of data into an array and hand this over to a lightweight memory stream and do the reading of the individual components there.

The problem is that the current MemorySrream of .NET does only allow an array in the constructor, but I would need a Stream that is able to handle Span or Memor for example. There is a ReadOnlyMemoryStream as an internal class deeply buried in the .NET source code.

The interesting thing is though that the ReadOnlyMemoryStream is slower than the MemoryStream where I would have thought it shouldn't make a big difference.

Is there any better implementation?

2 Answers

If you have a Span, you're already as fast as it gets, just read straight through it instead of plopping a stream on top of it.

A Span even gives you access to really nifty things like straight struct mapping without copies (MemoryMarshal.Cast), span increments (the equivalent to a stream advancing, part of Unsafe.Add), block copies if actually necessary (Unsafe.Copy) etc.

Related