Skip to content

Instantly share code, notes, and snippets.

@eoinahern
Created March 29, 2020 22:34
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 eoinahern/69b6403c6448a275434f6591b09f64c9 to your computer and use it in GitHub Desktop.
Save eoinahern/69b6403c6448a275434f6591b09f64c9 to your computer and use it in GitHub Desktop.
a Memoizer class from the book joy of kotlin
import java.util.concurrent.ConcurrentHashMap
class Memoizer<T, U> private constructor() {
private val map = ConcurrentHashMap<T, U>()
private fun callLocalMemoize(block: (T) -> U): (T) -> U = { input ->
map.computeIfAbsent(input) {
block(it)
}
}
companion object {
fun <T, U> memoize(inputFun: (T) -> U): (T) -> U {
return Memoizer<T, U>().callLocalMemoize(inputFun)
}
}
}
fun main() {
val myFun: (Int) -> Int = { x ->
Thread.sleep(1000)
x
}
val getNumberFun = Memoizer.memoize(myFun)
val timeOne = System.currentTimeMillis()
val num1 = getNumberFun(2)
val timeTwo = System.currentTimeMillis()
println("time1 : ${timeTwo - timeOne} : $num1")
val timeThree = System.currentTimeMillis()
val num2 = getNumberFun(2)
val timeFour = System.currentTimeMillis()
println("time2 : ${timeFour - timeThree} : $num2")
val anotherFun: (Triple<Int, Int, Int>) -> Int =
{ triple -> myFun(triple.first) + myFun(triple.second) + myFun(triple.third) }
val addNums = Memoizer.memoize(anotherFun)
val startTime = System.currentTimeMillis()
addNums(Triple(1, 2, 3))
val endTime = System.currentTimeMillis()
println("time taken : ${endTime - startTime}")
val startTime2 = System.currentTimeMillis()
addNums(Triple(1, 2, 3))
val endTime2 = System.currentTimeMillis()
//outputs in approx zero time due to the key
println("time taken : ${endTime2 - startTime2}")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment