Swift Pitch: Borrowing Sequence
A sequence provides access to its elements through an
Iterator, and an iterator’snext()operation returns anElement?. For a sequence of noncopyable elements, this operation could only be implemented by consuming the elements of the iterated sequence, with theforloop taking ownership of the elements individually.While consuming iteration is sometimes what you want, borrowing iteration is equally important, serves as a better default for noncopyable elements, and yet cannot be supported by the existing
Sequence.[…]
Instead of offering up individual elements via
next()asIteratorProtocoldoes,BorrowingIteratorProtocoloffers up spans of elements. The iterator indicates there are no more elements to iterate by returning an emptySpan.[…]
Note that in the case of
Array, the new protocol results in much less overhead for the optimizer to eliminate. Iterating aSpanin the inner loop is a lot closer to the “ideal” model of advancing a pointer over a buffer and accessing the elements directly. It is therefore expected that this design will result in better performance in some cases where today the optimizer is unable to eliminate the overhead of Swift’sArray.[…]
For this reason, it may not be appropriate to switch all
foriteration to useBorrowingSequencewhenSequenceis available. How to determine which cases are better (such asArrayis expected to be) and which are worse (such as theUnfoldSequenceexample above) needs further investigation. […] For now, if aSequenceconformance is available, it will be used even ifBorrowingSequenceis also available.
I haven’t had a need for noncopyable types, but I’m interested in reducing ARC overhead when traversing objects. Most of the time I don’t actually need to retain and release an object just to look at it briefly because I know that it’s not going to be removed from the collection.
Previously:
- Swift 6.2
- Swift Proposal: InlineArray
- Noncopyable Generics Walkthrough
- Swift Proposal: Noncopyable Structs and Enums
- Swift Pitch: “borrow” and “take” Parameter Ownership Modifiers
- Porting Graphing Calculator From C++ to Swift
- Swift @_assemblyVision
- Roadmap for Improving Swift Performance Predictability
- Swift Ownership Manifesto