Skip to content

Commit ff76106

Browse files
committed
[stdlib] don't copy array contents on removeAll(keepingCapacity: true)
1 parent 492da02 commit ff76106

File tree

3 files changed

+20
-3
lines changed

3 files changed

+20
-3
lines changed

stdlib/public/core/Array.swift

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1378,9 +1378,16 @@ extension Array: RangeReplaceableCollection {
13781378
if !keepCapacity {
13791379
_buffer = _Buffer()
13801380
}
1381-
else {
1381+
else if _buffer.isMutableAndUniquelyReferenced() {
13821382
self.replaceSubrange(indices, with: EmptyCollection())
13831383
}
1384+
else {
1385+
let buffer = _ContiguousArrayBuffer<Element>(
1386+
_uninitializedCount: 0,
1387+
minimumCapacity: capacity
1388+
)
1389+
_buffer = _Buffer(_buffer: buffer, shiftedToStartIndex: startIndex)
1390+
}
13841391
}
13851392

13861393
//===--- algorithms -----------------------------------------------------===//

stdlib/public/core/ArraySlice.swift

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1067,9 +1067,16 @@ extension ArraySlice: RangeReplaceableCollection {
10671067
if !keepCapacity {
10681068
_buffer = _Buffer()
10691069
}
1070-
else {
1070+
else if _buffer.isMutableAndUniquelyReferenced() {
10711071
self.replaceSubrange(indices, with: EmptyCollection())
10721072
}
1073+
else {
1074+
let buffer = _ContiguousArrayBuffer<Element>(
1075+
_uninitializedCount: 0,
1076+
minimumCapacity: capacity
1077+
)
1078+
_buffer = _Buffer(_buffer: buffer, shiftedToStartIndex: startIndex)
1079+
}
10731080
}
10741081

10751082
//===--- algorithms -----------------------------------------------------===//

stdlib/public/core/ContiguousArray.swift

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -975,9 +975,12 @@ extension ContiguousArray: RangeReplaceableCollection {
975975
if !keepCapacity {
976976
_buffer = _Buffer()
977977
}
978-
else {
978+
else if _buffer.isMutableAndUniquelyReferenced() {
979979
self.replaceSubrange(indices, with: EmptyCollection())
980980
}
981+
else {
982+
_buffer = _Buffer(_uninitializedCount: 0, minimumCapacity: capacity)
983+
}
981984
}
982985

983986
//===--- algorithms -----------------------------------------------------===//

0 commit comments

Comments
 (0)