Skip to content

Commit 46ed6c1

Browse files
committed
Avoid creating a yield ID counter per async writer
Motivation: The NIOAsyncWriter uses an atomic to generate yield IDs. Each writer has its own atomic. We can save an allocatiuon per writer but using a shared atomic. Each load then wrapping increment operation with relaxed ordering takes approx 3ns on my machine. For a UInt64 this would take approx 188 years to wrap around if run in a tight loop. Modification: - Share a single yield ID counter for NIOAsyncWriter Result: Fewer allocations
1 parent 9614996 commit 46ed6c1

File tree

1 file changed

+4
-2
lines changed

1 file changed

+4
-2
lines changed

Sources/NIOCore/AsyncSequences/NIOAsyncWriter.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,9 @@ import DequeModule
1717
import NIOConcurrencyHelpers
1818
import _NIODataStructures
1919

20+
@usableFromInline
21+
let yieldIDCounter = ManagedAtomic<UInt64>(0)
22+
2023
/// The delegate of the ``NIOAsyncWriter``. It is the consumer of the yielded writes to the ``NIOAsyncWriter``.
2124
/// Furthermore, the delegate gets informed when the ``NIOAsyncWriter`` terminated.
2225
///
@@ -435,13 +438,12 @@ extension NIOAsyncWriter {
435438
}
436439

437440
@usableFromInline
438-
/* private */ internal let _yieldIDCounter = ManagedAtomic<UInt64>(0)
439441

440442
@inlinable
441443
func generateUniqueYieldID() -> YieldID {
442444
// Using relaxed is fine here since we do not need any strict ordering just a
443445
// unique ID for every yield.
444-
.init(value: self._yieldIDCounter.loadThenWrappingIncrement(ordering: .relaxed))
446+
.init(value: yieldIDCounter.loadThenWrappingIncrement(ordering: .relaxed))
445447
}
446448
}
447449

0 commit comments

Comments
 (0)