What is optimal way to get TextReader instance from a Memory<byte> object?
I could write something like:
using (var stream = new MemoryStream(body.ToArray()))
using (var reader = new StreamReader(stream))
{
}
but maybe there is a better way?
What is optimal way to get TextReader instance from a Memory<byte> object?
I could write something like:
using (var stream = new MemoryStream(body.ToArray()))
using (var reader = new StreamReader(stream))
{
}
but maybe there is a better way?
StreamReaderwill dispose underlyingStreamautomatically.#1 The simpliest way
But here you're copying whole memory content into another array, it's memory-consuming and gives Garbage Collector more work. It's not recommended especially if array contains large amount of data.
There's another way of doing it without allocation of new array.
#2 The optimal way (recommended to save memory)
In other words
ArraySegmentreturns the source memory area as array.Tests
Here's an example to play with it (based on .NET Core 3.1 Console Application).
Output