Skip to content

Commit c887116

Browse files
committed
[stdlib] dropLast, prefix, suffix: ContiguousArray
Nano-optimization: Following the template used in methods `map` and `_filter`, internally use ContiguousArray before converting to an Array on return.
1 parent a1fb6f1 commit c887116

File tree

1 file changed

+12
-13
lines changed

1 file changed

+12
-13
lines changed

stdlib/public/core/Sequence.swift

Lines changed: 12 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -893,10 +893,9 @@ extension Sequence {
893893

894894
// FIXME: <rdar://problem/21885650> Create reusable RingBuffer<T>
895895
// Put incoming elements into a ring buffer to save space. Once all
896-
// elements are consumed, reorder the ring buffer into an `Array`
897-
// and return it. This saves memory for sequences particularly longer
898-
// than `maxLength`.
899-
var ringBuffer: [Element] = []
896+
// elements are consumed, reorder the ring buffer into a copy and return it.
897+
// This saves memory for sequences particularly longer than `maxLength`.
898+
var ringBuffer = ContiguousArray<Element>()
900899
ringBuffer.reserveCapacity(Swift.min(maxLength, underestimatedCount))
901900

902901
var i = 0
@@ -911,13 +910,13 @@ extension Sequence {
911910
}
912911

913912
if i != ringBuffer.startIndex {
914-
var rotated: [Element] = []
913+
var rotated = ContiguousArray<Element>()
915914
rotated.reserveCapacity(ringBuffer.count)
916915
rotated += ringBuffer[i..<ringBuffer.endIndex]
917916
rotated += ringBuffer[0..<i]
918-
return rotated
919-
} else {
920-
return ringBuffer
917+
return Array(rotated)
918+
} else {
919+
return Array(ringBuffer)
921920
}
922921
}
923922

@@ -975,8 +974,8 @@ extension Sequence {
975974
// holding tank into the result, an `Array`. This saves
976975
// `k` * sizeof(Element) of memory, because slices keep the entire
977976
// memory of an `Array` alive.
978-
var result: [Element] = []
979-
var ringBuffer: [Element] = []
977+
var result = ContiguousArray<Element>()
978+
var ringBuffer = ContiguousArray<Element>()
980979
var i = ringBuffer.startIndex
981980

982981
for element in self {
@@ -988,7 +987,7 @@ extension Sequence {
988987
i = (i + 1) % k
989988
}
990989
}
991-
return result
990+
return Array(result)
992991
}
993992

994993
/// Returns a sequence by skipping the initial, consecutive elements that
@@ -1070,15 +1069,15 @@ extension Sequence {
10701069
public __consuming func prefix(
10711070
while predicate: (Element) throws -> Bool
10721071
) rethrows -> [Element] {
1073-
var result: [Element] = []
1072+
var result = ContiguousArray<Element>()
10741073

10751074
for element in self {
10761075
guard try predicate(element) else {
10771076
break
10781077
}
10791078
result.append(element)
10801079
}
1081-
return result
1080+
return Array(result)
10821081
}
10831082
}
10841083

0 commit comments

Comments
 (0)