As far as I know, there is two main ways for converting a string
into MemoryStream.
MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(contents));
UnmanagedMemoryStream ums = UnmanagedMemoryStream(p.ToPointer(), 100);
or Marshal.Copy(p , buffer, 0, buffer.Length);
which is the same as #2
Instead of copying string
into byte[]
and then creating a MemoryStream
from it, I'm wondering to know if there is a nice workaround using ReadOnlyMemory<>
and/or Span<>
to create a MemoryStream
to gain more performant/efficient code (with zero GC operation and instant assignment)?
I know that "someStringContentFoo".AsMemory()
yields a ReadOnlyMemory<Char>
, but I just cannot convert it to a MemoryStream
.
Moreover, there is a Nuget package which converts ReadOnlyMemory<byte>
to MemoryStream
using AsStream()
Extension Method, but I cannot convert ReadOnlyMemory<char>
to ReadOnlyMemory<byte>
without using ToArray()
which sacrifices memory and GC.
Brief: Is there a way to convert string
to MemoryStream
without paying memory copy penalty?
question from:
https://stackoverflow.com/questions/65880054/generate-memory-stream-from-string-object-using-efficient-fashion-readonlymemor 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…