reserveCapacity(_:)
声明
mutating func reserveCapacity(_ minimumCapacity: Int)
参数
minimumCapacity
请求存储的元素数。
详述
如果要将已知数量的元素添加到数组中,请使用此方法来避免多次重新分配。此方法确保数组具有唯一的、可变的、连续的存储空间,并为至少请求数量的元素分配空间。
出于性能原因,新分配的存储大小可能大于请求的容量。使用数组的capacity
属性来确定新存储的大小。
保留阵列的几何增长策略
如果您实现由动态增长的数组支持的自定义数据结构,那么天真地调用reserveCapacity(_:)
方法可能会导致性能低于预期。数组需要遵循几何分配模式来附加元素以实现摊销 constant-time 性能。 Array
类型的 append(_:)
和 append(contentsOf:)
方法会为您处理这个细节,但 reserveCapacity(_:)
只分配您告诉它的空间(填充到一个圆形值),仅此而已。这避免了over-allocation,但可能导致插入没有摊销constant-time 性能。
以下代码声明了 values
,一个整数数组和 addTenQuadratic()
函数,该函数在每次调用时将另外十个值添加到 values
数组。
var values: [Int] = [0, 1, 2, 3]
// Don't use 'reserveCapacity(_:)' like this
func addTenQuadratic() {
let newCount = values.count + 10
values.reserveCapacity(newCount)
for n in values.count..<newCount {
values.append(n)
}
}
对 reserveCapacity(_:)
的调用每次通过 addTenQuadratic()
时都会将 values
数组的容量增加 10 个元素,这是线性增长。当多次调用平均时,该函数可能会衰减到 values.count
中的线性性能,而不是具有恒定的时间。这几乎肯定不是你想要的。
在这种情况下,最简单的解决方法通常是简单地删除对 reserveCapacity(_:)
的调用,并让 append(_:)
方法为您增长数组。
func addTen() {
let newCount = values.count + 10
for n in values.count..<newCount {
values.append(n)
}
}
如果您需要对阵列容量进行更多控制,请实施您自己的几何增长策略,将您计算的大小传递给 reserveCapacity(_:)
。
可用版本
相关用法
- Swift ContiguousArray reduce(_:_:)用法及代码示例
- Swift ContiguousArray replaceSubrange(_:with:)用法及代码示例
- Swift ContiguousArray reversed()用法及代码示例
- Swift ContiguousArray removeSubrange(_:)用法及代码示例
- Swift ContiguousArray removeFirst(_:)用法及代码示例
- Swift ContiguousArray removeAll(where:)用法及代码示例
- Swift ContiguousArray removeFirst()用法及代码示例
- Swift ContiguousArray reduce(into:_:)用法及代码示例
- Swift ContiguousArray reverse()用法及代码示例
- Swift ContiguousArray remove(at:)用法及代码示例
- Swift ContiguousArray randomElement(using:)用法及代码示例
- Swift ContiguousArray randomElement()用法及代码示例
- Swift ContiguousArray forEach(_:)用法及代码示例
- Swift ContiguousArray insert(contentsOf:at:)用法及代码示例
- Swift ContiguousArray lexicographicallyPrecedes(_:)用法及代码示例
- Swift ContiguousArray elementsEqual(_:)用法及代码示例
- Swift ContiguousArray isEmpty用法及代码示例
- Swift ContiguousArray suffix(from:)用法及代码示例
- Swift ContiguousArray endIndex用法及代码示例
- Swift ContiguousArray split(separator:maxSplits:omittingEmptySubsequences:)用法及代码示例
- Swift ContiguousArray sort()用法及代码示例
- Swift ContiguousArray firstIndex(of:)用法及代码示例
- Swift ContiguousArray contains(_:)用法及代码示例
- Swift ContiguousArray first(where:)用法及代码示例
- Swift ContiguousArray append(contentsOf:)用法及代码示例
注:本文由纯净天空筛选整理自apple.com大神的英文原创作品 ContiguousArray reserveCapacity(_:)。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。