Memoization has gotten us quite far along the path of building a sufficiently fast spellchecker, but we’re still not fast enough. In this section, we’ll look at another factor that can impact the performance of our programs: the shape of our data structures and the way we store and access memory in our programs.

You saw in the last section that when we started using ST to memoize a map of results, we ended up taking a significant performance penalty. It turns out that when we’re trying to get the best performance out of our applications, there are a few factors we need to think about beyond algorithmic complexity:

  • Avoiding indirection by having too many thunks that need to be evaluated for any particular value

  • Avoiding using mutable references to immutable data structures, creating a lot of unexpected copying when we update the value in the reference

  • Being mindful of the cost of traversing our data structure to access particular elements

In this section, we’ll look at the vectors library, and some of the efficient data structures that it provides for writing more high performance code.

What is a Vector?

Throughout this book, we’ve made heavy use of lists whenever we needed a simple flat collection of data. Lists are a popular choice in Haskell because they have a lot of library support, there’s special syntax that makes working with them convenient, and in most cases code written with lists is fast enough we don’t have to worry about performance. As we look to writing more compute-bound and data-intensive applications, lists start to show some weaknesses. Before we dive into the weaknesses of lists, and the ways other data structures can improve on lists, let’s review a simplified definition of a list:

​  ​ data ​ ​ List ​ a = ​ EmptyList ​ | ​ Cons ​ a (​ List ​ a)

In other words, each list is either an empty list, or it’s a value and a reference to the tail of the list. When we want to write efficient programs, this data structure can cause a couple of problems. First, to get to any element in the list, we have to traverse the entire list. If you want to get to the 1000th element of a list, your only option is to start at the beginning and walk one element at a time until you get to the 1000th element. The second problem is that each time you move from the head of a list to its tail, you might end up moving into a completely different part of memory. In an average Haskell program, we might not care very much about the cost of traversing a few elements in a list, or even a few hundred, and we certainly won’t concern ourselves with things like the physical layout of memory, but these factors can end up dominating the performance profile of certain applications.

When we care about efficiently storing and accessing memory, instead of linked lists we’re better off to use a contiguous slab of memory. If we know how much memory every item in the array will take, then we can get to any particular element directly without having to walk through all of the other elements. If we’re dealing with several elements of the array, we can fetch them all at once, and let the CPU cache them so that we don’t have to wait for the data at each index to be fetched.

There are several different ways to create and work with arrays in Haskell. The GHC.Arr module in base provides a fairly basic interface to dealing with arrays of values, and the primitives core library offers another low-level interface to arrays. Both of these modules offer basic array functionality, but most applications use the vectors library, which offers a rich and well-optimized interface on top of arrays that allows you to write more idiomatic code while still getting good performance.

A Quick Intro to Working with Vectors

The vector library is fairly large because it supports many different kinds of vectors for different use-cases. We’ll look at a couple of different kinds of vectors in the upcoming sections, but in most cases you can start with basic vectors by importing Data.Vector . This module exports a number of functions that conflict with list functions from Prelude , so it’s common to use qualified imports for vector modules:

​  ​ module ​ ​ VectorDemo ​ ​ where ​
​  ​ import ​ ​ qualified ​ ​ Data.Vector ​ ​ as ​ Vec

In most cases, this is all that you’ll need to do. You can create a vector from a list using toList , or create a vector an element at a time using Vec.cons :

​  vectorOfNumbers :: ​ Vec ​.​ Vector ​ ​ Int ​
​  vectorOfNumbers = ​ Vec ​.fromList [1..10]
​  
​  vectorRange :: ​ Int ​ -> ​ Int ​ -> ​ Vec ​.​ Vector ​ ​ Int ​
​  vectorRange a b
​  | a == b = ​ Vec ​.empty
​  | otherwise = ​ Vec ​.cons a $ vectorRange (a + 1) b

In general, the functions to work with vectors are similar enough to the functions that you’ve already seen for working with lists that we won’t spend much time on the specifics. You can review the vector documentation on Hackage [21] for a complete overview.

Spellchecking with Vectors

Now that you know a little bit about the vectors library, let’s jump into the implementation:

​  ​ module ​ ​ SpellCheck.STVec ​ ​ where ​
​  ​ import ​ ​ Data.Text ​ (​ Text ​)
​  ​ import ​ ​ qualified ​ ​ Data.Text ​ ​ as ​ T
​  ​ import ​ ​ Prelude ​ ​ hiding ​ (​ length ​, ​ read ​, ​ words ​)
​  ​ import ​ ​ Data.Foldable ​ (​ for_ ​)
​  ​ import ​ ​ Control.Monad.ST ​
​  ​ import ​ ​ qualified ​ ​ Data.Vector.Mutable ​ ​ as ​ MVec
​  
​  editDistance :: ​ Text ​ -> ​ Text ​ -> ​ Int ​
​  editDistance stringA stringB = runST $ ​ do ​
​  ​ let ​
​  aLen = ​ T ​.length stringA
​  bLen = ​ T ​.length stringB
​  as = zip [1..] (​ T ​.unpack stringA)
​  bs = zip [1..] (​ T ​.unpack stringB)
​  lookupIndex x y = (y * (aLen + 1)) + x
​  cache <- ​ MVec ​.new $ (aLen + 1) * (bLen + 1)
​  for_ [0..aLen] $ ​ \ ​idx -> ​ MVec ​.write cache (lookupIndex idx 0) idx
​  for_ [0..bLen] $ ​ \ ​idx -> ​ MVec ​.write cache (lookupIndex 0 idx) idx
​  for_ as $ ​ \ ​(idxA, charA) -> ​ do ​
​  for_ bs $ ​ \ ​(idxB, charB) -> ​ do ​
​  ​ let ​
​  cost = ​ if ​ charA == charB ​ then ​ 0 ​ else ​ 1
​  insertCost <- (1 +) <$>
​  ​ MVec ​.read cache (lookupIndex (idxA - 1) idxB)
​  deleteCost <- (1 +) <$>
​  ​ MVec ​.read cache (lookupIndex idxA (idxB - 1))
​  swapCost <- (cost +) <$>
​  ​ MVec ​.read cache (lookupIndex (idxA - 1) (idxB - 1))
​  ​ MVec ​.write cache (lookupIndex idxA idxB) $
​  minimum [swapCost, insertCost, deleteCost]
​  ​ MVec ​.read cache $ lookupIndex aLen bLen

You’ll notice this version of our algorithm looks different on the surface than the previous versions we’ve looked at. Instead of using recursion, we’ve switched to an iterative implementation that steps through the strings character by character and calculates the cost of the current edit. We’re also initializing some elements in our vector before we start looking at the edit distance. The initialization of the vectors is equivalent to the part of our recursive algorithm where, if one of our input strings is empty, we return the length of the remaining string. Instead of handling that in our inner loop, we precalculate those costs for each point in our two strings, and set them in the vector ahead of time.

The remainder of our algorithm isn’t all that different from the previous versions we’ve implemented, but the order we access the elements will be slightly different. In part, this approach illustrates how we can apply more traditional procedural algorithms with mutable data when writing pure Haskell functions. An additional benefit to being mindful about how we access data inside of vectors is locality . When we’re running code, it’s better to work with data that’s already cached by the CPU, since it’ll take longer to fetch it from memory than to access the local cache. Modern CPUs are pretty good at prefetching data from memory and caching it, but it works best when the data we’re accessing is physically close together in memory. When we’re working with data structures like lists and maps, we’re storing references to pieces of memory that may be further away. Unlike those structures, a Vector is stored in a contiguous block of memory. That means we can sometimes see some extra benefits from CPU caching if we’re careful about how we access the elements of a vector.

Minor algorithmic differences aside, the major change from our previous map-based cache implementation is that we’re no longer working with an STRef to an immutable data structure. Instead, we’re able to take advantage of mutability directly in our vector. Rather than making a copy of the cache for each change, we can directly modify memory in our vector as we calculate the edit distances between different parts of our string. Hopefully this will help us reclaim some of the performance that we lost when we originally switched to ST , but let’s compile and profile our application to find out:

​  found 173 suggested matches
​  1,567,828,368 bytes allocated in the heap
​  9,104 bytes copied during GC
​  12,167,208 bytes maximum residency (4 sample(s))
​  780,248 bytes maximum slop
​  28 MiB total memory in use (0 MB lost due to fragmentation)
​  Tot time (elapsed) Avg pause Max pause
​  Gen 0 375 colls, 0 par 0.007s 0.007s 0.0000s 0.0001s
​  Gen 1 4 colls, 0 par 0.006s 0.006s 0.0016s 0.0041s
​  INIT time 0.000s ( 0.000s elapsed)
​  MUT time 0.695s ( 0.695s elapsed)
​  GC time 0.013s ( 0.013s elapsed)
​  RP time 0.000s ( 0.000s elapsed)
​  PROF time 0.000s ( 0.000s elapsed)
​  EXIT time 0.000s ( 0.000s elapsed)
​  Total time 0.708s ( 0.708s elapsed)
​  %GC time 0.0% (0.0% elapsed)
​  Alloc rate 2,256,217,778 bytes per MUT second
​  Productivity 98.1% of total user, 98.1% of total elapsed
​  real 0m0.775s
​  user 0m0.740s
​  sys 0m0.028s

That’s much better! Compared to our fast list-based memoized implementation, our new ST -based function uses the same amount of total memory, but does half the total number of memory allocations, and runs almost twice as fast! We’re still at over half a second per word that we want to spellcheck, so we’re not quite fast enough, but the switch to a vector type we can update directly has had some clear benefits to the overall performance of our application.