Skip to content

Instantly share code, notes, and snippets.

@kylef kylef/performance.swift Secret
Last active Aug 29, 2015

Embed
What would you like to do?
#!/usr/bin/env swift -Ounchecked
/*
Performance testing of imperative and declarative solutions to the same problem.
Example from "Practical Declarative Programming" presented at 360 iDev in 2015.
*/
import func CoreFoundation.CFAbsoluteTimeGetCurrent
func imperativeMap() {
let groups = [
["Kyle", "Katie"],
["André", "Maxine", "Ash"],
]
var counts = [Int]()
for group in groups {
let people = group.count
counts.append(people)
}
}
func declarativeMap() {
let groups = [
["Kyle", "Katie"],
["André", "Maxine", "Ash"],
]
groups.map { $0.count }
}
let amount = 1_000_0000
func time(closure:(() -> ())) -> Double {
let start = CFAbsoluteTimeGetCurrent()
for _ in (0..<amount) {
closure()
}
let end = CFAbsoluteTimeGetCurrent()
return end - start
}
let declarativeTime = time(declarativeMap)
let imperativeTime = time(imperativeMap)
print("Total time taken for 1 million iterations.")
print("Declarative: \(declarativeTime)s")
print("Imperative: \(imperativeTime)s")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.