Swift reduce高阶函数与for循环运行效率比较

1、打印代码执行时长的方法

func calculateRunTime(_ closure: () -> Void) {
    let startTime = CFAbsoluteTimeGetCurrent()
    closure()
    let endTime = CFAbsoluteTimeGetCurrent()
    debugPrint("代码执行时长:%f 毫秒", (endTime - startTime) * 1000)
}

2、运行代码
计算0~10000整数的和

var nums = [Int]()
for i in 0...10000 {
    nums.append(i)
}
calculateRunTime {
    var sum = 0
    for i in nums {
        sum += i
    }
    debugPrint("for循环:\(sum)")
}
calculateRunTime {
    let sum = nums.reduce(0) { $0 + $1 }
    debugPrint("reduce:\(sum)")
}

运行结果:

"for循环:50005000"
"代码执行时长:%f 毫秒" 2.7080774307250977
"reduce:50005000"
"代码执行时长:%f 毫秒" 2.714991569519043

从运行结果可以看出,reduce高阶函数运行效率不for循环低一点

你可能感兴趣的:(Swift reduce高阶函数与for循环运行效率比较)