From cee48fd87d0ae541cefeee4880d2e419631e9368 Mon Sep 17 00:00:00 2001 From: George Barnett Date: Tue, 22 Sep 2020 11:17:19 +0100 Subject: [PATCH] Remove a few unnecessary allocations. (#243) Motivation: Unnecessary allocations are bad! Modifications: - Use 'removeAll' instead of allocating a new buffer when dropping pending reads in the 'HTTP2StreamChannel' - Use a static empty buffer in 'DataBuffer.evacuatePendingWrites' Result: - Fewer allocations. - Resolves #240 - Resolves #241 --- .../NIOHTTP2/Frame Buffers/OutboundFlowControlBuffer.swift | 5 ++++- Sources/NIOHTTP2/HTTP2StreamChannel.swift | 4 ++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/Sources/NIOHTTP2/Frame Buffers/OutboundFlowControlBuffer.swift b/Sources/NIOHTTP2/Frame Buffers/OutboundFlowControlBuffer.swift index 7db2b5e..576b33a 100644 --- a/Sources/NIOHTTP2/Frame Buffers/OutboundFlowControlBuffer.swift +++ b/Sources/NIOHTTP2/Frame Buffers/OutboundFlowControlBuffer.swift @@ -250,6 +250,9 @@ private struct DataBuffer { return self.bufferedChunks.hasMark } + /// An empty buffer, we use this avoid an allocation in 'evacuatePendingWrites'. + private static let emptyBuffer = MarkedCircularBuffer(initialCapacity: 0) + init() { self.bufferedChunks = MarkedCircularBuffer(initialCapacity: 8) self.flushedBufferedBytes = 0 @@ -307,7 +310,7 @@ private struct DataBuffer { /// Removes all pending writes, invalidating this structure as it does so. mutating func evacuatePendingWrites() -> MarkedCircularBuffer { - var buffer = MarkedCircularBuffer(initialCapacity: 0) + var buffer = DataBuffer.emptyBuffer swap(&buffer, &self.bufferedChunks) return buffer } diff --git a/Sources/NIOHTTP2/HTTP2StreamChannel.swift b/Sources/NIOHTTP2/HTTP2StreamChannel.swift index 96b3416..735774e 100644 --- a/Sources/NIOHTTP2/HTTP2StreamChannel.swift +++ b/Sources/NIOHTTP2/HTTP2StreamChannel.swift @@ -649,8 +649,8 @@ final class HTTP2StreamChannel: Channel, ChannelCore { private extension HTTP2StreamChannel { /// Drop all pending reads. private func dropPendingReads() { - /// To drop all the reads, as we don't need to report it, we just allocate a new buffer of 0 size. - self.pendingReads = CircularBuffer(initialCapacity: 0) + /// We don't need to report the dropped reads, just remove them all. + self.pendingReads.removeAll() } /// Deliver all pending reads to the channel.