Swift中数组容量的扩容机制具体是怎样的?
Swift数组扩容机制的测试与观察
我之前在Apple官方文档中看到这样的说明:
When you add elements to an array and that array begins to exceed its reserved capacity, the array allocates a larger region of memory and copies its elements into the new storage. The new storage is a multiple of the old storage’s size.
为了实际验证这个扩容逻辑,我在Playground里创建了几个测试示例。第一个示例的结果看起来完全符合文档的描述:
var array = [1, 2, 3, 4, 5] array.capacity // 输出:5 array.append(contentsOf: [6, 7, 8, 9, 10]) array.capacity // 输出:10 array.append(11) array.capacity // 输出:20
但是……
内容的提问来源于stack exchange,提问作者Roberto Sampaio
相关产品推荐
相关产品推荐

