Skip to content

Instantly share code, notes, and snippets.

@BradBroulik
Last active March 12, 2017 14:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BradBroulik/8824476d6c8e35ddd9da7c84982b0496 to your computer and use it in GitHub Desktop.
Save BradBroulik/8824476d6c8e35ddd9da7c84982b0496 to your computer and use it in GitHub Desktop.
Swift forEach vs map vs for-in performance test
/// measure calls a block for a specified number of iterations and returns the execution time in seconds
func measure(name: String = "", iterations: Int = 10, forBlock block: () -> Void) -> Double {
let startDate = Date()
for _ in 0..<iterations {
block()
}
let endDate = Date()
let timeInterval: Double = endDate.timeIntervalSince(startDate)
print("\(name):\t \(timeInterval) seconds")
return timeInterval
}
/// Test data
func createUUIDs() -> [UUID] {
return Array(repeating: UUID(), count: 1000)
}
/// Performance tests
let input = createUUIDs()
measure(name: "forEach", iterations: 1, forBlock: {
var outputA = [String]()
input.forEach({ outputA.append($0.description) })
})
measure(name: "map", iterations: 1, forBlock: {
let outputB = input.map({ $0.description })
})
measure(name: "for-in", iterations: 1, forBlock: {
var outputC = [String]()
for i in input {
outputC.append(i.description)
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment