Optimize out an array allocation
authorCory Nelson <phrosty@gmail.com>
Thu, 11 Jul 2019 02:55:38 +0000 (19:55 -0700)
committerCory Nelson <phrosty@gmail.com>
Thu, 11 Jul 2019 03:07:26 +0000 (20:07 -0700)
Commit migrated from https://github.com/dotnet/corefx/commit/69b57934d5fa13147b44908e5a9d9d2e01e5d9bc

src/libraries/System.Net.Http/src/System/Net/Http/SocketsHttpHandler/Http2Connection.cs

index 0f7523a..78ef3c2 100644 (file)
@@ -581,8 +581,7 @@ namespace System.Net.Http
 
             // Send PING ACK
             // Don't wait for completion, which could happen asynchronously.
-            byte[] pingContent = _incomingBuffer.ActiveMemory.Slice(0, FrameHeader.PingLength).ToArray();
-            LogExceptions(SendPingAckAsync(pingContent));
+            LogExceptions(SendPingAckAsync(_incomingBuffer.ActiveMemory.Slice(0, FrameHeader.PingLength)));
 
             _incomingBuffer.Discard(frameHeader.Length);
         }
@@ -792,6 +791,10 @@ namespace System.Net.Http
         {
             Debug.Assert(pingContent.Length == FrameHeader.PingLength);
 
+            // copy pingContent before we go async so the caller can
+            // discard their buffer without waiting for us to complete.
+            long pingContentLong = BitConverter.ToInt64(pingContent.Span);
+
             Memory<byte> writeBuffer = await StartWriteAsync(FrameHeader.Size + FrameHeader.PingLength).ConfigureAwait(false);
             if (NetEventSource.IsEnabled) Trace("Started writing.");
 
@@ -799,7 +802,7 @@ namespace System.Net.Http
             frameHeader.WriteTo(writeBuffer);
             writeBuffer = writeBuffer.Slice(FrameHeader.Size);
 
-            pingContent.CopyTo(writeBuffer);
+            BitConverter.TryWriteBytes(writeBuffer.Span, pingContentLong);
 
             FinishWrite(mustFlush: false);
         }