简体   繁体   中英

Will `removeLast` ever reduce the capacity of an array in swift?

我知道.append有时会增加一个数组的容量并形成一个新的数组副本,但是.removeLast会反过来这个并通过复制到一个新的更小的数组来减少数组的容量吗?

No (or at least if it is yes, it is a bug (*)). That would violate its complexity promise.

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

Complexity: Amortized O(1) over many additions. If the array uses a bridged NSArray instance as its storage, the efficiency is unspecified.

"Amortized O(1) over many additions" means that for any given operation it may not be O(1), but the limit as the number of elements goes towards infinity is O(1) because larger and larger pre-allocations will be made, and so reallocations will become more and more infrequent.

Now read the complexity promise for removeLast() :

Complexity: O(1)

There's nowhere for a reallocation to hide in there (or at the very least it could not be implemented "by copying into a new smaller array").

(*) There's a difficult exception to this. Any mutation on an Array is subject to possible copy-on-write. That means that any mutation, no matter its performance promises, may become O(n) if it shares storage with another Array. This makes reasoning about Swift performance very challenging, but is not specific to this question.

As Rob Napier's answer points out, no, removeFirst should not reduce the capacity of the array. Adding some details, removeLast doesn't either, and removeAll does by default , though it takes a parameter keepingCapacity to change that behavior.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM