Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

.net

.net-core

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?

like image 936
msedi Avatar asked Jan 18 '26 08:01

msedi


1 Answers

Yes, there is such an extension method, provided by Microsoft.Toolkit.HighPerformance package

  • see Microsoft.Toolkit.HighPerformance.Extensions Namespace for the doc
  • code can be found at code
like image 109
Shmil The Cat Avatar answered Jan 21 '26 08:01

Shmil The Cat



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!