如果您的数组在整个程序过程中的大小都非常大,那么将数组声明为它将达到的最大大小然后控制您的程序可以访问多少数组会更有效,或者在整个程序过程中非常频繁地更改数组的大小?
最佳答案
来自Swift headers ,这是关于阵列增长和容量的:
When an array's contiguous storage fills up, new storage must be allocated and elements must be moved to the new storage. Array, ContiguousArray, and Slice share an exponential growth strategy that makes append a constant time operation when amortized over many invocations. In addition to a
count
property, these array types have acapacity
that reflects their potential to store elements without reallocation, and when you know how many elements you'll store, you can callreserveCapacity
to pre-emptively reallocate and prevent intermediate reallocations.
读到这里,我会说最好保留你需要的容量,只有当你发现它确实是个问题时才回来优化它。如果你一直假装长度,你会为自己做更多的工作。
关于arrays - 在 Swift 中, append 数组的效率如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26727427/