Skip to content

Instantly share code, notes, and snippets.

@kylef
Last active August 29, 2015 14:27
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 kylef/de49799f0c0894d7374d to your computer and use it in GitHub Desktop.
Save kylef/de49799f0c0894d7374d to your computer and use it in GitHub Desktop.
#!/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