Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
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