We’ve narrowed down our immediate performance problem to recalculating the same edit distances many times. The question now is, what can we do about that? One option is to simply avoid recalculating distances that we’ve already calculated once. If we replace our editDistance function with a version that remembers arguments it’s been called with, and the results that were returned, then we can use the cached values rather than recomputing the distance whenever we encounter a familiar pair of strings. This is a technique called memoization , and it’s common in many different languages and styles of programming.

When we want to memoize a function, Haskell offers us both some benefits and some challenges. The most immediate benefit is that, being a pure language, most Haskell code lends itself to being memoized without having to do any extra work. The same purity that makes our functions good candidates for memoization also makes the memoization itself a bit more challenging, since we need to be thoughtful about how we do the memoization. In this section, we’ll look at two different approaches that you can use for memoization: first through automatic memoization using thunks, and second by using internal mutability to manually cache values.

Memoization (Almost) for Free

The first approach to memoization that we’ll look at takes advantage of laziness to create a list of edit distances between all of the different points in our two strings. When we first create this list, all of the elements will be unevaluated thunks, so we don’t need to pay the cost of actually computing the distance up front. Once we’ve created a list of unevaluated thunks, we can replace the recursive calls inside of our edit function with a lookup into our list of values. Any time we come upon an unevaluated thunk, it will call our edit function again, completing the recursive call we would have made directly. If we find an evaluated thunk, then nothing needs to be evaluated, and we can simply return the distance that we’ve already calculated.

The only thing we need to do for this approach to work is to turn the arguments of our editDistance function into something that lends itself to being used to look up elements in the list of cached results. This isn’t always possible; thankfully, in this case we have an obvious solution: rather than iterating over each character in our input strings, we can iterate over a numeric index into the strings. Before we move on to memoization, let’s take an intermediate step and refactor our function to use indexes in our strings, rather than using the characters directly. Since we’ll be working on a new implementation that you might want to compare to the original naive version, let’s put this implementation in our SpellCheck.ListMemo module:

​  ​ module ​ ​ SpellCheck.ListMemo ​ ​ where ​
​  ​ import ​ ​ Data.Text ​ (​ Text ​)
​  ​ import ​ ​ qualified ​ ​ Data.Text ​ ​ as ​ T
​  ​ import ​ ​ Types ​
​  
​  editDistance :: ​ Text ​ -> ​ Text ​ -> ​ Int ​
​  editDistance stringA stringB =
​  getEditDistance 0 0
​  ​ where ​
​  aLen = ​ T ​.length stringA
​  bLen = ​ T ​.length stringB
​  getEditDistance idxA idxB
​  | idxA == aLen = bLen - idxB
​  | idxB == bLen = aLen - idxA
​  | stringA `​ T ​.index` idxA == stringB `​ T ​.index` idxB =
​  getEditDistance (idxA + 1) (idxB + 1)
​  | otherwise =
​  ​ let ​
​  deleteCost = getEditDistance (idxA + 1) idxB
​  insertCost = getEditDistance idxA (idxB + 1)
​  swapCost = getEditDistance (idxA + 1) (idxB + 1)
​  ​ in ​ 1 + minimum [deleteCost, insertCost, swapCost]

As you can see, we haven’t had to change much in our editDistance implementation. You’ll notice that we’re using the T.index function now rather than T.head . This function lets us access a character at a particular offset inside of a Text value. It’s a partial function, but we’re testing the index to make sure it’s not out of bounds in an earlier guard clause, so we’re safe to use it here. The only other notable difference is that our original editDistance code has been moved into a where clause. This will come in handy when we add memoization.

Before we move on, you can add another entry to your list of benchmarks and profile this index-based implementation of our naive algorithm. You should notice from the profiling results that our new index-based implementation is slightly faster and uses somewhat less memory. We’re saving a little bit of work by avoiding creating copies of each substring that we’re evaluating, but we haven’t yet addressed the amount of duplicate work we’re doing. Until we avoid recomputing the distance for the same strings, we’re going to be severely limited in the performance we can get out of our program. So, let’s update our function to start memoizing results.

The first thing we need to do is add a cache of values. Our edit distance function takes two arguments—the length of each string. We need to map that to a single cache. We’ll do that by storing our cache as a list of lists. For each index in our first string, we’ll store a list of cached distances to every point in our second string:

​  distances =
​  map (​ \ ​idxA -> map (getEditDistance idxA) [0..bLen]) [0..aLen]

Remember, when we first define distances it’s a list of unevaluated thunks. When we evaluate a particular element of the list, it will return another list of unevaluated thunks. Each of those thunks will call getEditDistance the first time we need to get their value.

Now that we have a cache of values, we need a way to look up a particular value. Let’s add a function to help make this easier:

​  lookupEditDistance idxA idxB =
​  distances !! idxA !! idxB

The last thing we need to do is replace the recursive calls to getEditDistance with calls to lookupEditDistance . The final version of our memoized function looks like this:

​  editDistance :: ​ Text ​ -> ​ Text ​ -> ​ Int ​
​  editDistance stringA stringB =
​  lookupEditDistance 0 0
​  ​ where ​
​  distances =
​  map (​ \ ​idxA -> map (getEditDistance idxA) [0..bLen]) [0..aLen]
​  lookupEditDistance idxA idxB =
​  distances !! idxA !! idxB
​  aLen = ​ T ​.length stringA
​  bLen = ​ T ​.length stringB
​  getEditDistance idxA idxB
​  | idxA == aLen = bLen - idxB
​  | idxB == bLen = aLen - idxA
​  | stringA `​ T ​.index` idxA == stringB `​ T ​.index` idxB =
​  lookupEditDistance (idxA + 1) (idxB + 1)
​  | otherwise =
​  ​ let ​
​  deleteCost = lookupEditDistance (idxA + 1) idxB
​  insertCost = lookupEditDistance idxA (idxB + 1)
​  swapCost = lookupEditDistance (idxA + 1) (idxB + 1)
​  ​ in ​ 1 + minimum [deleteCost, insertCost, swapCost]

As with the move to an index-based function, the overall impact to our code by adding a memoization cache is pretty small. We added a couple of new bindings and replaced calls to getEditDistance with calls to lookupEditDistance . Let’s profile this version and see what kind of performance improvement we’ve gotten by putting our potentially repeated work behind a thunk:

​  user@host$ time cabal exec spellcheck -- \
​  ./words.txt ./helllo.txt quiet spellcheck-list-memo +RTS -s -p
​  
​  found 173 suggested matches
​  3,716,439,504 bytes allocated in the heap
​  21,632 bytes copied during GC
​  12,084,472 bytes maximum residency (4 sample(s))
​  781,064 bytes maximum slop
​  27 MiB total memory in use (0 MB lost due to fragmentation)
​  
​  Tot time (elapsed) Avg pause Max pause
​  Gen 0 897 colls, 0 par 0.012s 0.012s 0.0000s 0.0001s
​  Gen 1 4 colls, 0 par 0.007s 0.007s 0.0018s 0.0048s
​  INIT time 0.000s ( 0.000s elapsed)
​  MUT time 1.573s ( 1.573s elapsed)
​  GC time 0.019s ( 0.019s elapsed)
​  RP time 0.000s ( 0.000s elapsed)
​  PROF time 0.000s ( 0.000s elapsed)
​  EXIT time 0.000s ( 0.000s elapsed)
​  Total time 1.593s ( 1.593s elapsed)
​  %GC time 0.0% (0.0% elapsed)
​  Alloc rate 2,361,897,083 bytes per MUT second
​  Productivity 98.8% of total user, 98.8% of total elapsed
​  
​  real 0m1.656s
​  user 0m1.623s
​  sys 0m0.027s

Amazingly, these few small changes have saved us around an order of magnitude in runtime! If we look at the profiling output, we can verify that we’ve also substantially reduced the number of calls to editDistance from 15590594654 calls in our original un-memoized version down to 8066319 calls in our new version. By taking advantage of laziness and the fact that each thunk is only evaluated ones, we were able to reduce the number of calls to editDistance by over 99%!

Using a list or other data structure to cache the results of thunks as a way of memoizing function calls is an extremely effective low-effort technique for improving performance in your Haskell code, but there are a couple of things to watch out for. One decision to be mindful of is the data structure you are using to hold the cached values. Using the wrong data structure, or using a data structure in a less-than-optimal way, can have a big impact on how much memoization improves your program’s performance. For example, we stored the results of our function calls in a list, and it worked well enough because we are dealing with short strings, so the cost of traversing our list of cached values wasn’t very high. Our cache is also fairly dense , meaning we didn’t have very many elements of our list that we never evaluated. If we were spending more time traversing our list, or had a lot of elements we never looked at, the performance improvement wouldn’t have been as impressive. For example, let’s add 100 empty unevaluated thunks to the beginning of each of our cached lists:

​  ​ where ​
​  offset = 100
​  distances =
​  map
​  (​ \ ​idxA -> map
​  (​ \ ​idxB -> getEditDistance (idxA - offset) (idxB - offset)
​  ) [0..bLen + offset])
​  [0..aLen + offset]
​  lookupEditDistance idxA idxB =
​  distances !! (idxA + offset) !! (idxB + offset)

When we run this, we can see this version of the application increases both the total amount of allocated memory and the runtime by 10x.

You should also keep in mind that holding references to memoization caches longer than necessary can inflate the memory usage of your application. This happens most often if you create the cache as a top-level binding. Top-level bindings won’t be garbage collected, so accumulating a large collection of cached values in a long-running program can cause a space leak. Even without creating top-level bindings, you can inadvertently hold onto a reference to a cache from an unevaluated thunk. This is similar to the behavior you saw when you learned about IORefs earlier in this book.

One edge case that can come up when memoizing functions is caused by a compiler optimization called let floating . This is an optimization that GHC will sometimes perform that “lifts” a value outside of a function where it’s defined so that it can be re-used. When a large cache is floated out, it won’t get garbage collected between function calls and you can end up accumulating a lot of used memory. You can typically identify this by profiling your application and noticing that your cache is responsible for a larger percentage of allocations than you would have expected.

When you encounter this problem, one way to solve it is to disable let floating in the current module. You can do that on a per-module basis with the OPTIONS_GHC pragma, which lets you set compiler options on a per-module basis, and passing it the -fno-full-laziness argument, which disables let floating:

​  ​ {-# OPTIONS_GHC -fno-full-laziness #-} ​

Let-floating-induced space leaks aren’t common, and you shouldn’t necessarily avoid memoization or proactively disable let floating to avoid problems. Unfortunately, the infrequency of the problem also means it can be hard to remember to look for this as a cause if you find that your program is unexpectedly using too much memory.