Last active
April 2, 2017 19:19
-
-
Save berkus/8a9e104f8aac5d025eb5 to your computer and use it in GitHub Desktop.
A "fast" memoization generic in Swift
This file contains hidden or 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
Promised speed: | |
0.1s https://dl.dropboxusercontent.com/s/bpgountdjrbs17n/2014-06-09%20at%2019.00.png | |
Actual speed: | |
575s https://dl.dropboxusercontent.com/s/2kbn5p1g4t03fvl/2014-06-09%20at%2019.00%20%281%29.png | |
With optimizations: | |
$ time xcrun swift -i -Ofast memoize.swift | |
1.61803398874989 | |
608.42 real 304.25 user 144.19 sys |
This file contains hidden or 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
func memoize<T: Hashable, U>( body: ( (T)->U, T )->U ) -> (T)->U { | |
var memo = Dictionary<T, U>() | |
var result: ((T)->U)! | |
result = { x in | |
if let q = memo[x] { return q } | |
let r = body(result, x) | |
memo[x] = r | |
return r | |
} | |
return result | |
} | |
let fibonacci = memoize { | |
fibonacci, n in | |
n < 2 ? Double(n) : fibonacci(n-1) + fibonacci(n-2) | |
} | |
println(fibonacci(45)/fibonacci(44)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hey just wrote an in depth post this, might be interested read for you random googles :) https://medium.com/@mvxlr/swift-memoize-walk-through-c5224a558194#.sl4bfon3k