当处理非常大的数组(比如75000个样本)时,removeSubrange函数是否足够快?或者我应该用其他更快的方法。
我可以用两种方式使用removeSubrange,如下所示。计算时间有区别吗,特别是对于大样本。

 import UIKit

 var xt1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 var xt2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 xt1.removeSubrange(ClosedRange(uncheckedBounds: (lower: 7, upper: 9)))

 xt2.removeSubrange(7...9)

 print("Method 1:", xt1)

 print("Method 2:", xt2)

最佳答案

从文档removeSubrange
复杂度:O(n),其中n是集合的长度。
这么小的尺寸。

var x = Array(repeating: "yes", count: 750000)

我用布拉德·拉森的代码来测量:
func timeElapsedInSecondsWhenRunningCode(operation: ()->()) -> Double {
    let startTime = CFAbsoluteTimeGetCurrent()
    operation()
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    return Double(timeElapsed)
}

所以让我们试着测量一下。
timeElapsedInSecondsWhenRunningCode {
    x.removeSubrange(4543...72000)
}

需要0.03秒
现在你可以做一些测量并找出答案。
这是一个完整的代码,它将执行32次迭代来测量随机范围内的性能。
var x = Array(repeating: "yes", count: 750000)

func timeElapsedInSecondsWhenRunningCode(from: Int, to: Int, operation: ()->()) -> Double {
    let startTime = CFAbsoluteTimeGetCurrent()
    operation()
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    return Double(timeElapsed)
}

struct Test {
    var range:(Int, Int)
    var time:Double
}

var mesurments = [Int:Test]()

for i in 0...32 {

    let from  = randomInt(min: 0, max: x.count/2)

    let to = randomInt(min: from, max: x.count)

    let z = x

    let time = timeElapsedInSecondsWhenRunningCode(from: from, to: to, operation: {
            x.removeSubrange(from...to)
    })

    x = z

    mesurments[i] = Test(range: (from, to), time: time)
}


func randomInt(min: Int, max:Int) -> Int {
    return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}

08-19 21:57