繁体   English   中英

如何有效地将 append 项目转换为 Swift 中的大型 arrays?

[英]How to efficiently append items to large arrays in Swift?

我正在研究一个 Swift 项目,该项目涉及非常大的动态变化 arrays。 我遇到了一个问题,每次连续操作都比前者花费更长的时间。 我有理由确定这个问题是由附加到 arrays 引起的,因为我在一个简单的测试中遇到了同样的问题,它只是附加到一个大数组。

我的测试代码:

import Foundation

func measureExecution(elements: Int, appendedValue: Int) -> Void {
    var array = Array(0...elements)
    //array.reserveCapacity(elements)
    
    let start = DispatchTime.now()
    array.append(appendedValue)
    let end = DispatchTime.now()
    print(Double(end.uptimeNanoseconds - start.uptimeNanoseconds) / 1_000_000_000)
}

for i in 0...100 {
    measureExecution(elements: i*10000, appendedValue: 1)
}

这将尝试在 10000 和 1000000 之间的 100 个不同的数组大小,计时从 append 一个项目到数组末尾需要多长时间。 As I understand it, Swift arrays are dynamic arrays that will reallocate memory geometrically (it allocates more and more memory each time it needs to reallocate), which Apple's documentation says should mean appending a single element to an array is an O(1) operation when averaged over many calls to the append(_:) method当对 append(_:) 方法( sourceappending a single element to an array is an O(1) operation when averaged over many calls to the append(_:) method 因此,我认为 memory 分配不会导致问题。

但是,数组的长度与 append 一个元素所需的时间之间存在线性关系。 我绘制了一堆数组长度的时间图,并且排除了一些异常值,它很明显是 O(n)。 我还使用保留容量(在代码块中注释掉)运行了相同的测试,以确认 memory 分配不是问题,我得到了几乎相同的结果: 数组长度和追加时间图

如何有效地 append 结束大量 arrays (最好不使用reserveCapacity )?

根据我的阅读,Swift arrays 预分配存储。 每次填充 Array 的分配存储空间时,分配的空间都会增加一倍。 这样你就不会经常进行新的 memory 分配,也不会分配一堆你不需要的空间。

数组 class 确实有一个reserveCapacity(_:) 如果您知道要存储多少元素,您可能想尝试一下。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM