Tuesday, January 27, 2026

Swift Pitch: Borrowing Sequence

Ben Cohen:

A sequence provides access to its elements through an Iterator, and an iterator’s next() operation returns an Element?. For a sequence of noncopyable elements, this operation could only be implemented by consuming the elements of the iterated sequence, with the for loop 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() as IteratorProtocol does, BorrowingIteratorProtocol offers up spans of elements. The iterator indicates there are no more elements to iterate by returning an empty Span.

[…]

Note that in the case of Array, the new protocol results in much less overhead for the optimizer to eliminate. Iterating a Span in 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’s Array.

[…]

For this reason, it may not be appropriate to switch all for iteration to use BorrowingSequence when Sequence is available. How to determine which cases are better (such as Array is expected to be) and which are worse (such as the UnfoldSequence example above) needs further investigation. […] For now, if a Sequence conformance is available, it will be used even if BorrowingSequence is 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:

Comments RSS · Twitter · Mastodon

Leave a Comment