Swift - 學用 數組 Array

遍歷數組方法效率比較

//var hhArr = Set<Int>.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語言的遍歷慢的多

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章