Eliminate spurious MemoryStream allocation in ByteArrayContent (original) (raw)

ByteArrayContent's ctor calls HttpContent.SetBuffer:

SetBuffer(_content, _offset, _count);

Which then allocates a MemoryStream:

internal void SetBuffer(byte[] buffer, int offset, int count)
{
_bufferedContent = new MemoryStream(buffer, offset, count, writable: false, publiclyVisible: true);
}

This stream is not needed in the common case: if passing as a request content, it goes unused (or could be elided in other ways). It is only ever needed if the user calls GetStreamAsync() (or a few related ones) on their own content.

We should try to make this allocation only as needed, not every time. This also affects StringContent, which inherits from ByteArrayContent.