Memoization
In previous sections, we talked about functions as building blocks and explained that we can compose our applications with functions. If functions can be building blocks in our programs, then they should be cacheable! But how do we cache them? The answer is memoization.
Memoization is the process of storing the result of functions, given their input, in order to improve the performance of our programs. We can memoize pure functions as pure functions do not rely on external data and do not change anything outside themselves. Pure functions provide the same result for a given input every time. Therefore, we can save or cache the results (in other words, memoize the results) given their inputs and use them in the future without going through the calculation process.
To be able to understand the concept, let's look at the following example in which we will manually memoize the power2
function:
var memo = Dictionary<Int, Int>() func memoizedPower2(n: Int) -> Int { if...