Generate memory stream from String object using efficient fashion (ReadOnlyMemory/Span)

Viewed 196

As far as I know, there is two main ways for converting a string into MemoryStream.

  1. MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(contents));
  2. 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?

0 Answers
Related