Constructing a ByteArrayContent (or anything that derives from it, like StringContent) or a ReadOnlyMemoryContent proactively allocates a MemoryStream that it stores as the _bufferedContent on the base HttpContent. But the 99.99% use case for ByteArrayContent is as a request payload, and this _bufferedContent isn't used for that. The only time this would be used is if a developer created a ByteArrayContent and then explicitly got the stream from it, e.g. via GetStreamAsync, in which case we're no worse off by doing the creation lazily. This PR just deletes the unnecessary code / allocation.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
-using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
_content = content;
_offset = 0;
_count = content.Length;
-
- SetBuffer(_content, _offset, _count);
}
public ByteArrayContent(byte[] content, int offset, int count)
_content = content;
_offset = offset;
_count = count;
-
- SetBuffer(_content, _offset, _count);
}
protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) =>
get { return _bufferedContent != null; }
}
- internal void SetBuffer(byte[] buffer, int offset, int count)
- {
- _bufferedContent = new MemoryStream(buffer, offset, count, writable: false, publiclyVisible: true);
- }
-
internal bool TryGetBuffer(out ArraySegment<byte> buffer)
{
if (_bufferedContent != null)
// See the LICENSE file in the project root for more information.
using System.IO;
-using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
{
private readonly ReadOnlyMemory<byte> _content;
- public ReadOnlyMemoryContent(ReadOnlyMemory<byte> content)
- {
+ public ReadOnlyMemoryContent(ReadOnlyMemory<byte> content) =>
_content = content;
- if (MemoryMarshal.TryGetArray(content, out ArraySegment<byte> array))
- {
- // If we have an array, allow HttpClient to take optimized paths by just
- // giving it the array content to use as its already buffered data.
- SetBuffer(array.Array!, array.Offset, array.Count);
- }
- }
protected override Task SerializeToStreamAsync(Stream stream, TransportContext? context) =>
stream.WriteAsync(_content).AsTask();