Swift - 学用 数组 Array

文章目录

  • 遍历数组方法效率比较

遍历数组方法效率比较

//var hhArr = Set.init()
//
//for i in 0..<1000000 {
//    hhArr.insert(i)
//}

var hhArr: Array<Int> = [Int].init(repeating: 12, count: 1000000)

//forin 遍历
var stratTime = CACurrentMediaTime()
for num in hhArr {
}
var duration:String = String(format: "%.7f", (CACurrentMediaTime() - stratTime))
print("forin执行时间:        \(duration)")

//Range 遍历 (index,value)
stratTime = CACurrentMediaTime()
for index in 0..<hhArr.count {
}
duration = String(format: "%.7f", (CACurrentMediaTime() - stratTime))
print("Range执行时间:        \(duration) ")

//foreach 遍历 (index,value)
stratTime = CACurrentMediaTime()
hhArr.forEach { (value) in
}
duration = String(format: "%.7f", (CACurrentMediaTime() - stratTime))
print("forEach执行时间:      \(duration)")

//enmerated 遍历 (offset,value)
stratTime = CACurrentMediaTime()
for num in hhArr.enumerated() {
}
duration = String(format: "%.7f", (CACurrentMediaTime() - stratTime))
print("enmerated执行时间:    \(duration)")


//enmerated 赋值遍历 (index,value)
stratTime = CACurrentMediaTime()
for (index,value) in hhArr.enumerated() {
}
duration = String(format: "%.7f", (CACurrentMediaTime() - stratTime))
print("enmerated正执行时间:  \(duration)")

//enmerated 反向遍历 (index,value)
stratTime = CACurrentMediaTime()
for (index,value) in hhArr.enumerated().reversed() {
}
duration = String(format: "%.7f", (CACurrentMediaTime() - stratTime))
print("enmerated倒执行时间:  \(duration)")
stratTime = CACurrentMediaTime()

输出:

forin执行时间:        0.2368286
Range执行时间:        0.4636577 
forEach执行时间:      0.2391857
enmerated执行时间:    0.3148192
enmerated正执行时间:  0.3109440
enmerated倒执行时间:  0.6621849
enmerated执行时间:    0.3156892
enmerated正执行时间:  0.3125509
enmerated倒执行时间:  0.6486633

结论, 速度:
forin > forEach > enmerated正序 > enmerated倒序。
enmerated 遍历 取 (index, value) < 只取value, 但差别不大。
同样数量的Set集合要比数组遍历快的多
swift的遍历要比C语言的遍历慢的多

你可能感兴趣的:(macOS开发,iOS,开发,swift)