Swift是否足够快删除子范围?

时间:2017-10-30 10:13:44

标签: arrays swift performance

当处理非常大的数组时,例如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)

1 个答案:

答案 0 :(得分:1)

来自文档removeSubrange

  

复杂性:O(n),其中n是集合的长度。

对你来说这么小的测量。

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

我使用Brad Larson的代码进行测量:

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)))
}