title: Improving performance of higher order functions vs loops in Swift (3.0)
body: <pre><code>import XCTest
  
  class testTests: XCTestCase {
      static func makearray() -&gt; [Int] {
          var array: [Int] = []
          for x in 0..&lt;1000000 {
             array.append(x)
          }
          return array
      }
  
      let array = testTests.makearray()
  
      func testPerformanceExample() {
          self.measure {
              var result: [String] = []
              for x in self.array {
              let tmp = "string\(x)"
              if tmp.hasSuffix("1234") {
                  result.append(tmp)
              }
          }
          print(result.count)
      }
  }
  
  func testPerformanceExample2() {
      self.measure {
          let result = self.array.map { "string\($0)" }
                                 .filter { $0.hasSuffix("1234") }
          print(result.count)
      }
  }
  
  func testPerformanceExample3() {
      self.measure {
          let result = self.array.flatMap { int -&gt; String? in
              let tmp = "string\(int)"
              return tmp.hasSuffix("1234") ? tmp : nil
          }
          print(result.count)
      }
  }
  }
  </code></pre>
  
  <p>In this code I am trying to see how the higher order functions perform with respect to processing a large array.</p>
  
  <p>The 3 tests produce the same results with times of around 0.75s for loop, 1.38s map/filter, 1.21s flatmap.</p>
  
  <p>Assuming HOFs are, more or less, functions wrapping loops, this makes sense as in the map/filter case, it is looping through the first array for map, then looping through the result of that to filter.</p>
  
  <p>In the case of flatmap, is it doing the map first, and then able to do a simpler filter operation?</p>
  
  <p>Is my understanding of what is happening under the hood (roughly) correct?</p>
  
  <p>If so, would it be fair to say that the compiler is not able to do much optimisation of this?</p>
  
  <p>And finally, is there a better way of doing this? The HOF versions are definitely easier for me to understand, but for performance critical areas, it looks like for-loops are the way to go?</p>