Skip to content

Commit 4c14f58

Browse files
committed
[stdlib] don't copy array contents on removeAll(keepingCapacity: true)
1 parent 7392833 commit 4c14f58

File tree

3 files changed

+23
-3
lines changed

3 files changed

+23
-3
lines changed

stdlib/public/core/Array.swift

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1348,9 +1348,17 @@ extension Array: RangeReplaceableCollection {
13481348
if !keepCapacity {
13491349
_buffer = _Buffer()
13501350
}
1351-
else {
1351+
else if _buffer.isMutableAndUniquelyReferenced() {
13521352
self.replaceSubrange(indices, with: EmptyCollection())
13531353
}
1354+
else {
1355+
let buffer = _ContiguousArrayBuffer<Element>(
1356+
_uninitializedCount: capacity,
1357+
minimumCapacity: 0
1358+
)
1359+
buffer.count = 0
1360+
_buffer = _Buffer(_buffer: buffer, shiftedToStartIndex: startIndex)
1361+
}
13541362
}
13551363

13561364
//===--- algorithms -----------------------------------------------------===//

stdlib/public/core/ArraySlice.swift

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1067,9 +1067,17 @@ 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: capacity,
1076+
minimumCapacity: 0
1077+
)
1078+
buffer.count = 0
1079+
_buffer = _Buffer(_buffer: buffer, shiftedToStartIndex: startIndex)
1080+
}
10731081
}
10741082

10751083
//===--- algorithms -----------------------------------------------------===//

stdlib/public/core/ContiguousArray.swift

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -972,9 +972,13 @@ extension ContiguousArray: RangeReplaceableCollection {
972972
if !keepCapacity {
973973
_buffer = _Buffer()
974974
}
975-
else {
975+
else if _buffer.isMutableAndUniquelyReferenced() {
976976
self.replaceSubrange(indices, with: EmptyCollection())
977977
}
978+
else {
979+
_buffer = _Buffer(_uninitializedCount: capacity, minimumCapacity: 0)
980+
_buffer.count = 0
981+
}
978982
}
979983

980984
//===--- algorithms -----------------------------------------------------===//

0 commit comments

Comments
 (0)