Memoization is a technique that's used for speeding up function calls by caching and reusing the output instead of recomputing for a given set of inputs. This technique offers a trade-off between memory and speed. The typical applications are for computationally expensive functions or for recursive functions, which branch out calling the recursive function many times with the same values, such as Fibonacci.
Let's use the latter to explore the effects of memoization. Fibonacci itself can be implemented recursively in the following manner:
fun fib(k: Int): Long = when (k) { 0 -> 1 1 -> 1 else -> fib(k - 1) + fib(k - 2) }
Note that when we invoke fib(k), we need to invoke fib(k-1) and fib(k-2). However, fib(k-1) will itself invoke fib(k-2) and fib(k-3), and so on. The result is that we make many duplicated calls with the...