Avoid unnecessary heap allocation when parsing frame headers. (#107)

Motivation:

As noted in #105, I spotted that we were heap-allocating an array
when parsing the frame header. That heap allocation isn't necessary, we
can just write directly into an Int, which should save us some heap spray.

Modifications:

- Rewrote code to avoid heap allocating array and instead to use Int.
- Elided some bounds checks by using an unsafe pointer, since I was
    already here and it saved about 1% performance in a hot loop.

Result:

Fewer heap allocations on the hot code path.
This commit is contained in:
Cory Benfield authored and GitHub committed 2019-04-18 17:32:17 +01:00
1 parent ee31368790
commit 4cb9d07b54
1 file changed
+9 -9
+9 -9
View File
@@ -1159,17 +1159,17 @@ fileprivate struct FrameHeader {
fileprivate extension ByteBuffer {
mutating func readFrameHeader() -> FrameHeader? {
guard self.readableBytes >= 9 else {
return nil
let saveSelf = self
guard let lenHigh = self.readInteger(as: UInt16.self),
let lenLow = self.readInteger(as: UInt8.self),
let type = self.readInteger(as: UInt8.self),
let flags = self.readInteger(as: UInt8.self),
let rawStreamID = self.readInteger(as: UInt32.self) else {
self = saveSelf
return nil
}
let lenBytes: [UInt8] = self.readBytes(length: 3)!
let len = Int(lenBytes[0]) << 16 | Int(lenBytes[1]) << 8 | Int(lenBytes[2])
let type: UInt8 = self.readInteger()!
let flags: UInt8 = self.readInteger()!
let rawStreamID: UInt32 = self.readInteger()!
return FrameHeader(length: len, type: type, flags: FrameFlags(rawValue: flags), rawStreamID: rawStreamID)
return FrameHeader(length: Int(lenHigh) << 8 | Int(lenLow), type: type, flags: FrameFlags(rawValue: flags), rawStreamID: rawStreamID)
}
mutating func writePayloadSize(_ size: Int, at location: Int) {