extension Array {
/// Reverses the elements of the collection within a given range of indices.
///
/// - Parameter indices: A range of valid indices of the collection,
/// the elements of which will be reversed.
///
mutating func reverse(indices: Range<Index>) {
if isEmpty || indices.isEmpty { return }
var low = indices.lowerBound
var high = index(before: indices.upperBound)
while low < high {
swap(&self[low], &self[high])
formIndex(after: &low)
formIndex(before: &high)
}
}
}
The major bottleneck here appears to be with Sequence
's first(where:)
method. If we take a look at its implementationits implementation, we can see it's implemented as:
A simple fix to this problem is to simply define our own first(where:)
method for random-access collections that just uses a for-in loop for random-access collections. This allows us to take advantage of a more performant version of the method, while still allowing for complicated non-random-access collections to have a first(where:)
implementation that uses their (potentially) customised forEach(_:)
implementation.