[SR-13923] Array.removeAll(keepingCapacity: true) wastes time copying memory around when Array is not uniquely referenced #56321
Labels
Array
Area → standard library: The `Array` type
bug
A deviation from expected or documented behavior. Also: expected but undesirable behavior.
performance
run-time performance
standard library
Area: Standard library umbrella
unexpected behavior
Bug: Unexpected behavior or incorrect output
Environment
Apple Swift version 5.3.1 (swiftlang-1200.0.43 clang-1200.0.32.8)
Additional Detail from JIRA
md5: 724c0c846234a1ede0885d027c480e99
Issue Description:
Here's a simple (and stupid) Swift program:
This program is mostly noise to prevent the optimiser from killing the program, but at its root it allocates a big Array and then calls
workIt
in a loop.workIt
makes a copy of the array, removes all the elements from it (keeping capacity), and then iterates the (now empty) array and does some math.When run under time profiler in Instruments this program spends all of its time (and it is a noticeable amount of time) in
memmove
. This is because the implementation ofArray.removeAll(keepingCapacity🙂
is pessimistic forkeepingCapacity=true
:replaceSubrange
is extremely general, and so it keeps the contents of the Array as it is. This means, if the Array is not uniquely referenced, it wastes its time copying over the entire contents of the buffer, which it then promptly throws away.The text was updated successfully, but these errors were encountered: