Skip to content

Commit

Permalink
Remove a few unnecessary allocations.
Browse files Browse the repository at this point in the history
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
  • Loading branch information
glbrntt committed Sep 22, 2020
1 parent 6722647 commit 88b0582
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -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<BufferElement>(initialCapacity: 0)

init() {
self.bufferedChunks = MarkedCircularBuffer(initialCapacity: 8)
self.flushedBufferedBytes = 0
Expand Down Expand Up @@ -307,7 +310,7 @@ private struct DataBuffer {

/// Removes all pending writes, invalidating this structure as it does so.
mutating func evacuatePendingWrites() -> MarkedCircularBuffer<BufferElement> {
var buffer = MarkedCircularBuffer<BufferElement>(initialCapacity: 0)
var buffer = DataBuffer.emptyBuffer
swap(&buffer, &self.bufferedChunks)
return buffer
}
Expand Down
4 changes: 2 additions & 2 deletions Sources/NIOHTTP2/HTTP2StreamChannel.swift
Original file line number Diff line number Diff line change
Expand Up @@ -620,8 +620,8 @@ final class HTTP2StreamChannel<Message: HTTP2FramePayloadConvertible & HTTP2Fram
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.
Expand Down

0 comments on commit 88b0582

Please sign in to comment.