-
-
Save kylef/de49799f0c0894d7374d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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