From 87c78de6b48fcfaea7eaefd3e8a2ad2eac2ed636 Mon Sep 17 00:00:00 2001 From: Karoy Lorentey Date: Wed, 31 Aug 2022 13:53:52 -0700 Subject: [PATCH] =?UTF-8?q?[Deque]=20Force-inline=20the=20subscript?= =?UTF-8?q?=E2=80=99s=20=5Fmodify=20accessor=20to=20work=20around=20a=20pe?= =?UTF-8?q?rformance=20issue?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Resolves #164. (cherry picked from commit 98cd75386634e3b8ffdba64eee93fd5b5a6a732d) --- Sources/DequeModule/Deque+Collection.swift | 33 ++++++++++++++-------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/Sources/DequeModule/Deque+Collection.swift b/Sources/DequeModule/Deque+Collection.swift index 61ba34a2..a5b8c334 100644 --- a/Sources/DequeModule/Deque+Collection.swift +++ b/Sources/DequeModule/Deque+Collection.swift @@ -359,25 +359,36 @@ extension Deque: RandomAccessCollection { handle.ptr(at: slot).pointee = newValue } } + @inline(__always) // https://github.com/apple/swift-collections/issues/164 _modify { precondition(index >= 0 && index < count, "Index out of bounds") - _storage.ensureUnique() - // We technically aren't supposed to escape storage pointers out of a - // managed buffer, so we escape a `(slot, value)` pair instead, leaving - // the corresponding slot temporarily uninitialized. - var (slot, value) = _storage.update { handle -> (_Slot, Element) in - let slot = handle.slot(forOffset: index) - return (slot, handle.ptr(at: slot).move()) - } + var (slot, value) = _prepareForModify(at: index) defer { - _storage.update { handle in - handle.ptr(at: slot).initialize(to: value) - } + _finalizeModify(slot, value) } yield &value } } + @inlinable + internal mutating func _prepareForModify(at index: Int) -> (_Slot, Element) { + _storage.ensureUnique() + // We technically aren't supposed to escape storage pointers out of a + // managed buffer, so we escape a `(slot, value)` pair instead, leaving + // the corresponding slot temporarily uninitialized. + return _storage.update { handle in + let slot = handle.slot(forOffset: index) + return (slot, handle.ptr(at: slot).move()) + } + } + + @inlinable + internal mutating func _finalizeModify(_ slot: _Slot, _ value: Element) { + _storage.update { handle in + handle.ptr(at: slot).initialize(to: value) + } + } + /// Accesses a contiguous subrange of the deque's elements. /// /// - Parameters: