Skip to content

Instantly share code, notes, and snippets.

@skolima
Created October 23, 2025 10:45
Show Gist options
  • Select an option

  • Save skolima/96d057586da3cb8e52ad597f5a11206c to your computer and use it in GitHub Desktop.

Select an option

Save skolima/96d057586da3cb8e52ad597f5a11206c to your computer and use it in GitHub Desktop.
// zero-copy BinaryData creation from MemoryStream
var stream = new MemoryStream();
stream.Write([1, 2, 3]); // some data is written to the memory stream
stream.Flush();
// this requires a memory copy
var dataViaStreamCopy = BinaryData.FromStream(stream);
// this does not require a memory copy
var dataViaBufferAccess = new BinaryData(stream.GetBuffer().AsMemory(0, (int)stream.Position));
// what BinaryData does internally is the same:
// https://github.com/dotnet/dotnet/blob/main/src/runtime/src/libraries/System.Memory.Data/src/System/BinaryData.cs#L305
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment