# Swift的性能：map（）和reduce（）vs for循环

` `// Populate array with 1,000,000,000 random numbers var array = [Float](count: 1_000_000_000, repeatedValue: 0) for i in 0..<array.count { array[i] = Float(random()) } let start = NSDate() // Construct a new array, with each element from the original multiplied by 5 let output = array.map({ (element) -> Float in return element * 5 }) // Log the elapsed time let elapsed = NSDate().timeIntervalSinceDate(start) print(elapsed)` `

` `var output = [Float]() for element in array { output.append(element * 5) }` `

`map`平均执行时间：20.1秒。 `for`循环的平均执行时间：11.2秒。 使用整数而不是浮点的结果是相似的。

` `// Populate array with 1,000,000 random numbers var array = [Float](count: 1_000_000, repeatedValue: 0) for i in 0..<array.count { array[i] = Float(random()) } let start = NSDate() // Perform operation 100,000 times for _ in 0..<100_000 { let sum = array.reduce(0, combine: {\$0 + \$1}) } // Log the elapsed time let elapsed = NSDate().timeIntervalSinceDate(start) print(elapsed)` `

VS：

` `for _ in 0..<100_000 { var sum: Float = 0 for element in array { sum += element } }` `

`reduce`方法需要29秒，而`for`循环需要（显然）0.000003秒。

`map`这样的函数和`reduce`接受函数作为input来`reduce` ，这使得优化器把它放在一个更大的压力。 在这种情况下，一些非常激进的优化的自然诱惑就是不断地在`map`的实现和你提供的闭包之间来回切换，同样在这些不同的代码分支之间传输数据（通过寄存器和堆栈通常）。

` `output.reserveCapacity(array.count)` `

` `for _ in 0..<100_000 { var sum: Float = 0 for element in array { sum += element } }` `

` `for _ in 0..<100_000 { let sum = array.reduce(0, combine: {\$0 + \$1}) }` `

` `do { var total = Float(0.0) let start = NSDate() for _ in 0..<100_000 { total += array.reduce(0, combine: {\$0 + \$1}) } let elapsed = NSDate().timeIntervalSinceDate(start) print("sum with reduce:", elapsed) print(total) } do { var total = Float(0.0) let start = NSDate() for _ in 0..<100_000 { var sum = Float(0.0) for element in array { sum += element } total += sum } let elapsed = NSDate().timeIntervalSinceDate(start) print("sum with loop:", elapsed) print(total) }` `