Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
250 views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/65880054/generate-memory-stream-from-string-object-using-efficient-fashion-readonlymemor

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...