Will `removeLast` ever reduce array capacity in swift?

I know that it .appendwill sometimes increase the capacity of the array and form a new copy of the array, but will .removeLastit ever cancel it and reduce the capacity of the array by copying it to a new smaller array?

+4
source share
2 answers

No (or at least, if so, this is a mistake (*)). This will violate its complexity.

If you read the promise of complexity for append, it reads:

Complexity: Depreciation O (1) for many additions. If the array uses a bridged instance of NSArray as storage, performance is not indicated.

" O (1) " , O (1), , , O (1), pre- , .

removeLast():

: O (1)

, (, , ) ).

(*) . . , , promises, O (n), . Swift , .

+4

, , removeFirst . , removeLast , removeAll , keepingCapacity.

var arr = [Int]()
print(arr.capacity)    // 0
arr.append(1)
print(arr.capacity)    // 2
arr.append(2)
print(arr.capacity)    // 2
arr.removeFirst()
print(arr.capacity)    // 2
arr.removeLast()
print(arr.capacity)    // 2 (though the array is now empty)
arr.removeAll(keepingCapacity: true)
print(arr.capacity)    // 2
arr.removeAll()
print(arr.capacity)    // 0
+2

Source: https://habr.com/ru/post/1663023/


All Articles