Skip to content

Commit 4bf379b

Browse files
authored
Implement faster pointer rebasing. (#1696)
Motivation: I recently discovered that UnsafeRawBufferPointer.init(rebasing:) is surprisingly expensive, with 7 traps and 11 branches. A simple replacement can make it a lot cheaper, down to two traps and four branches. This ends up having pretty drastic effects on ByteBuffer-heavy NIO code, which often outlines the call to that initializer and loses the ability to make a bunch of site-local optimisations. While this has been potentially fixed upstream with swiftlang/swift#34879, there is no good reason to wait until Swift 5.4 for this improvement. Due to the niche use-case, I didn't bother doing this for _every_ rebasing in the program. In particular, there is at least one UnsafeBufferPointer(rebasing:) that I didn't do this with, and there are uses in both NIOTLS and NIOHTTP1 that I didn't change. While we can fix those if we really need to, it would be nice to avoid this helper proliferating too far through our codebase. Modifications: - Replaced the use of URBP.init(rebasing:) with a custom hand-rolled version that avoids Slice.count. Result: Cheaper code. One NIOHTTP2 benchmark sees a 2.9% speedup from this change alone.
1 parent 44d67ba commit 4bf379b

File tree

5 files changed

+56
-15
lines changed

5 files changed

+56
-15
lines changed

Sources/NIO/ByteBuffer-aux.swift

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ extension ByteBuffer {
3434
// this is not technically correct because we shouldn't just bind
3535
// the memory to `UInt8` but it's not a real issue either and we
3636
// need to work around https://bugs.swift.org/browse/SR-9604
37-
Array<UInt8>(UnsafeRawBufferPointer(rebasing: ptr[range]).bindMemory(to: UInt8.self))
37+
Array<UInt8>(UnsafeRawBufferPointer(fastRebase: ptr[range]).bindMemory(to: UInt8.self))
3838
}
3939
}
4040

@@ -139,7 +139,7 @@ extension ByteBuffer {
139139
}
140140
return self.withUnsafeReadableBytes { pointer in
141141
assert(range.lowerBound >= 0 && (range.upperBound - range.lowerBound) <= pointer.count)
142-
return String(decoding: UnsafeRawBufferPointer(rebasing: pointer[range]), as: Unicode.UTF8.self)
142+
return String(decoding: UnsafeRawBufferPointer(fastRebase: pointer[range]), as: Unicode.UTF8.self)
143143
}
144144
}
145145

@@ -210,7 +210,7 @@ extension ByteBuffer {
210210
self.withVeryUnsafeMutableBytes { destCompleteStorage in
211211
assert(destCompleteStorage.count >= index + allBytesCount)
212212
let dest = destCompleteStorage[index ..< index + allBytesCount]
213-
dispatchData.copyBytes(to: .init(rebasing: dest), count: dest.count)
213+
dispatchData.copyBytes(to: .init(fastRebase: dest), count: dest.count)
214214
}
215215
return allBytesCount
216216
}
@@ -228,7 +228,7 @@ extension ByteBuffer {
228228
return nil
229229
}
230230
return self.withUnsafeReadableBytes { pointer in
231-
return DispatchData(bytes: UnsafeRawBufferPointer(rebasing: pointer[range]))
231+
return DispatchData(bytes: UnsafeRawBufferPointer(fastRebase: pointer[range]))
232232
}
233233
}
234234

@@ -396,7 +396,7 @@ extension ByteBuffer {
396396
precondition(count >= 0, "Can't write fewer than 0 bytes")
397397
self.reserveCapacity(index + count)
398398
self.withVeryUnsafeMutableBytes { pointer in
399-
let dest = UnsafeMutableRawBufferPointer(rebasing: pointer[index ..< index+count])
399+
let dest = UnsafeMutableRawBufferPointer(fastRebase: pointer[index ..< index+count])
400400
_ = dest.initializeMemory(as: UInt8.self, repeating: byte)
401401
}
402402
return count

Sources/NIO/ByteBuffer-core.swift

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -379,7 +379,7 @@ public struct ByteBuffer {
379379

380380
@inlinable
381381
mutating func _setBytesAssumingUniqueBufferAccess(_ bytes: UnsafeRawBufferPointer, at index: _Index) {
382-
let targetPtr = UnsafeMutableRawBufferPointer(rebasing: self._slicedStorageBuffer.dropFirst(Int(index)))
382+
let targetPtr = UnsafeMutableRawBufferPointer(fastRebase: self._slicedStorageBuffer.dropFirst(Int(index)))
383383
targetPtr.copyMemory(from: bytes)
384384
}
385385

@@ -389,7 +389,7 @@ public struct ByteBuffer {
389389
mutating func _setSlowPath<Bytes: Sequence>(bytes: Bytes, at index: _Index) -> _Capacity where Bytes.Element == UInt8 {
390390
func ensureCapacityAndReturnStorageBase(capacity: Int) -> UnsafeMutablePointer<UInt8> {
391391
self._ensureAvailableCapacity(_Capacity(capacity), at: index)
392-
let newBytesPtr = UnsafeMutableRawBufferPointer(rebasing: self._slicedStorageBuffer[Int(index) ..< Int(index) + Int(capacity)])
392+
let newBytesPtr = UnsafeMutableRawBufferPointer(fastRebase: self._slicedStorageBuffer[Int(index) ..< Int(index) + Int(capacity)])
393393
return newBytesPtr.bindMemory(to: UInt8.self).baseAddress!
394394
}
395395
let underestimatedByteCount = bytes.underestimatedCount
@@ -513,7 +513,7 @@ public struct ByteBuffer {
513513
public mutating func withUnsafeMutableReadableBytes<T>(_ body: (UnsafeMutableRawBufferPointer) throws -> T) rethrows -> T {
514514
self._copyStorageAndRebaseIfNeeded()
515515
let readerIndex = self.readerIndex
516-
return try body(.init(rebasing: self._slicedStorageBuffer[readerIndex ..< readerIndex + self.readableBytes]))
516+
return try body(.init(fastRebase: self._slicedStorageBuffer[readerIndex ..< readerIndex + self.readableBytes]))
517517
}
518518

519519
/// Yields the bytes currently writable (`bytesWritable` = `capacity` - `writerIndex`). Before reading those bytes you must first
@@ -529,7 +529,7 @@ public struct ByteBuffer {
529529
@inlinable
530530
public mutating func withUnsafeMutableWritableBytes<T>(_ body: (UnsafeMutableRawBufferPointer) throws -> T) rethrows -> T {
531531
self._copyStorageAndRebaseIfNeeded()
532-
return try body(.init(rebasing: self._slicedStorageBuffer.dropFirst(self.writerIndex)))
532+
return try body(.init(fastRebase: self._slicedStorageBuffer.dropFirst(self.writerIndex)))
533533
}
534534

535535
/// This vends a pointer of the `ByteBuffer` at the `writerIndex` after ensuring that the buffer has at least `minimumWritableBytes` of writable bytes available.
@@ -587,7 +587,7 @@ public struct ByteBuffer {
587587
@inlinable
588588
public func withUnsafeReadableBytes<T>(_ body: (UnsafeRawBufferPointer) throws -> T) rethrows -> T {
589589
let readerIndex = self.readerIndex
590-
return try body(.init(rebasing: self._slicedStorageBuffer[readerIndex ..< readerIndex + self.readableBytes]))
590+
return try body(.init(fastRebase: self._slicedStorageBuffer[readerIndex ..< readerIndex + self.readableBytes]))
591591
}
592592

593593
/// Yields a buffer pointer containing this `ByteBuffer`'s readable bytes. You may hold a pointer to those bytes
@@ -605,7 +605,7 @@ public struct ByteBuffer {
605605
public func withUnsafeReadableBytesWithStorageManagement<T>(_ body: (UnsafeRawBufferPointer, Unmanaged<AnyObject>) throws -> T) rethrows -> T {
606606
let storageReference: Unmanaged<AnyObject> = Unmanaged.passUnretained(self._storage)
607607
let readerIndex = self.readerIndex
608-
return try body(.init(rebasing: self._slicedStorageBuffer[readerIndex ..< readerIndex + self.readableBytes]),
608+
return try body(.init(fastRebase: self._slicedStorageBuffer[readerIndex ..< readerIndex + self.readableBytes]),
609609
storageReference)
610610
}
611611

Sources/NIO/ByteBuffer-int.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ extension ByteBuffer {
6262
return self.withUnsafeReadableBytes { ptr in
6363
var value: T = 0
6464
withUnsafeMutableBytes(of: &value) { valuePtr in
65-
valuePtr.copyMemory(from: UnsafeRawBufferPointer(rebasing: ptr[range]))
65+
valuePtr.copyMemory(from: UnsafeRawBufferPointer(fastRebase: ptr[range]))
6666
}
6767
return _toEndianness(value: value, endianness: endianness)
6868
}

Sources/NIO/ControlMessage.swift

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ struct UnsafeControlMessageStorage: Collection {
5252
/// Get the part of the buffer for use with a message.
5353
public subscript(position: Int) -> UnsafeMutableRawBufferPointer {
5454
return UnsafeMutableRawBufferPointer(
55-
rebasing: self.buffer[(position * self.bytesPerMessage)..<((position+1) * self.bytesPerMessage)])
55+
fastRebase: self.buffer[(position * self.bytesPerMessage)..<((position+1) * self.bytesPerMessage)])
5656
}
5757

5858
var startIndex: Int { return 0 }
@@ -239,7 +239,7 @@ struct UnsafeOutboundControlBytes {
239239
private mutating func appendGenericControlMessage<PayloadType>(level: CInt,
240240
type: CInt,
241241
payload: PayloadType) {
242-
let writableBuffer = UnsafeMutableRawBufferPointer(rebasing: self.controlBytes[writePosition...])
242+
let writableBuffer = UnsafeMutableRawBufferPointer(fastRebase: self.controlBytes[writePosition...])
243243

244244
let requiredSize = NIOBSDSocketControlMessage.space(payloadSize: MemoryLayout.stride(ofValue: payload))
245245
precondition(writableBuffer.count >= requiredSize, "Insufficient size for cmsghdr and data")
@@ -263,7 +263,7 @@ struct UnsafeOutboundControlBytes {
263263
if writePosition == 0 {
264264
return UnsafeMutableRawBufferPointer(start: nil, count: 0)
265265
}
266-
return UnsafeMutableRawBufferPointer(rebasing: self.controlBytes[0 ..< self.writePosition])
266+
return UnsafeMutableRawBufferPointer(fastRebase: self.controlBytes[0 ..< self.writePosition])
267267
}
268268

269269
}

Sources/NIO/PointerHelpers.swift

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
//===----------------------------------------------------------------------===//
2+
//
3+
// This source file is part of the SwiftNIO open source project
4+
//
5+
// Copyright (c) 2017-2018 Apple Inc. and the SwiftNIO project authors
6+
// Licensed under Apache License v2.0
7+
//
8+
// See LICENSE.txt for license information
9+
// See CONTRIBUTORS.txt for the list of SwiftNIO project authors
10+
//
11+
// SPDX-License-Identifier: Apache-2.0
12+
//
13+
//===----------------------------------------------------------------------===//
14+
15+
// MARK: Rebasing shims
16+
17+
// These methods are shimmed in to NIO until https://github.com/apple/swift/pull/34879 is resolved.
18+
// They address the fact that the current rebasing initializers are surprisingly expensive and do excessive
19+
// checked arithmetic. This expense forces them to often be outlined, reducing the ability to optimise out
20+
// further preconditions and branches.
21+
extension UnsafeRawBufferPointer {
22+
@inlinable
23+
init(fastRebase slice: Slice<UnsafeRawBufferPointer>) {
24+
let base = slice.base.baseAddress?.advanced(by: slice.startIndex)
25+
self.init(start: base, count: slice.endIndex &- slice.startIndex)
26+
}
27+
28+
@inlinable
29+
init(fastRebase slice: Slice<UnsafeMutableRawBufferPointer>) {
30+
let base = slice.base.baseAddress?.advanced(by: slice.startIndex)
31+
self.init(start: base, count: slice.endIndex &- slice.startIndex)
32+
}
33+
}
34+
35+
extension UnsafeMutableRawBufferPointer {
36+
@inlinable
37+
init(fastRebase slice: Slice<UnsafeMutableRawBufferPointer>) {
38+
let base = slice.base.baseAddress?.advanced(by: slice.startIndex)
39+
self.init(start: base, count: slice.endIndex &- slice.startIndex)
40+
}
41+
}

0 commit comments

Comments
 (0)