arrays - 在 Swift 中, append 数组的效率如何?

标签 arrays swift append

如果您的数组在整个程序过程中的大小都非常大,那么将数组声明为它将达到的最大大小然后控制您的程序可以访问多少数组会更有效,或者在整个程序过程中非常频繁地更改数组的大小?

最佳答案

来自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 a capacity that reflects their potential to store elements without reallocation, and when you know how many elements you'll store, you can call reserveCapacity to pre-emptively reallocate and prevent intermediate reallocations.

读到这里,我会说最好保留你需要的容量,只有当你发现它确实是个问题时才回来优化它。如果你一直假装长度,你会为自己做更多的工作。

关于arrays - 在 Swift 中, append 数组的效率如何?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26727427/

相关文章:

java - 如何检查某些数字是否出现在数组中?

ios - 在 iPhone 5s 上的 iOS 8 Swift 上使用 NSUserDefaults 后启动时出现 EXC_BREAKPOINT,而不是模拟器

ios - 章节标题困惑

ios - 通过 UIActivityController 共享视频 PHAsset

javascript - 带有 href 和 javascript 的 jQuery append 元素不起作用

python - 无论我做什么都无法将数据 append 到文件

java - 用中间的回车符分割字符串(JAVA)

javascript - 如何从 JavaScript 中的数组中删除 null、undefined、NaN、0s、false 和空字符串?

javascript - 如何判断数组中的元素是否重复?

jQuery .each 与 jQuery select追加冲突