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(_:)。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。