Spellchecking is an easy feature to take for granted. Spellchecking has been available for personal computers since the 1980s, and most software we use to write text today has spellchecking available. Surprisingly, spellchecking continues to be both a relevant problem domain, and one that can present some interesting challenges when we need to write efficient code. In the first part of this chapter, we’ll build a general purpose spellchecking library that can be used with any dictionary.

Let’s start by creating a new cabal project. You’ll want to add a few dependencies to your project so you can follow along with this chapter:

  • base
  • containers
  • text
  • vector

We’ll start our project by building a performance naive spellchecking implementation, so let’s make a module named SpellCheck.Naive and add a couple of imports:

​  ​ module ​ ​ SpellCheck.Naive ​ ​ where ​
​  ​ import ​ ​ Data.Text ​ (​ Text ​)
​  ​ import ​ ​ qualified ​ ​ Data.Text ​ ​ as ​ T

To implement a spellchecker, we need to write two functions. First, we need a way to check to see how similar a misspelled word is to a correctly spelled word. This will help us identify the potential corrections we will suggest to the user when they have a typo. Second, we’ll need to check the words in the document we want to spellcheck against a dictionary of correctly spelled words, so that we can find words that need correction.

We can find out how similar two words are to one another using an edit distance metric . There are a few well-known examples of these that you can find online. The one we’ll use is called Levenshtein distance . It will tell us how many changes we’d need to make to turn one string into another string when we’re allowed to

  • Add a letter to the string,
  • Delete a letter from the string, or
  • Replace a letter in the string with a different one.

Before we move onto the implementation, let’s look at a couple of examples to get a better idea of what’s happening. First, we’ll try looking at the edit distance between identical strings:

​  λ editDistance "hello" "hello"
​  0

Since there are no changes to be made, the edit distance is 0. If we add some letters to either string, we’ll see that the edit distance increases with the number of letters that we’ve added:

​  λ editDistance "hello" "helloo"
​  1
​  λ editDistance "hello12345" "hello"
​  5

In these examples, we can see that for each extra letter, the edit distance increases by one. It doesn’t matter whether we add letters to the first string or the second string, since inserting a character and deleting a character both have the cost of a single edit. Next, let’s replace some letters with different letters:

​  λ editDistance "aaa" "aab"
​  1
​  λ editDistance "aaa" "abb"
​  2

Here, you can see that replacing the wrong letter with a correct letter costs a single edit. In the examples, each time we need to replace an “a” with a “b” it adds a single edit to the edit distance.

Finally, our algorithm should always return the smallest number of edits necessary to make the strings match up:

​  λ editDistance "bababa" "ababab"
​  2

At first you might be surprised that the edit distance is 2. If we swapped out every “b” for an “a”, and every “a” for a “b” we’d have a total edit distance of 6. We can accomplish the same thing in two edits by deleting the initial “b”, which costs one edit and gives us “ababa”, and then adding a “b” back to the end of the string, which costs us one more edit and gets our strings matching.

Surprisingly, there’s a pretty straightforward algorithm to find the edit distance between two strings. Let’s start by looking at the implementation, and then step through how it works:

​  editDistance :: ​ Text ​ -> ​ Text ​ -> ​ Int ​
​  editDistance stringA stringB
​  | ​ T ​.null stringA = ​ T ​.length stringB
​  | ​ T ​.null stringB = ​ T ​.length stringA
​  | ​ T ​.head stringA == ​ T ​.head stringB = editDistance restOfA restOfB
​  | otherwise = 1 + minimum [insertCost, deleteCost, swapCost]
​  ​ where ​
​  restOfA = ​ T ​.tail stringA
​  restOfB = ​ T ​.tail stringB
​  deleteCost = editDistance restOfA stringB
​  insertCost = editDistance stringA restOfB
​  swapCost = editDistance restOfA restOfB

Our implementation is made up of three basic rules:

First, if either string is empty, then the edit distance is equal to the length of the other string. We’re implementing this rule with the first two guard clauses in our function:

​  editDistance :: ​ Text ​ -> ​ Text ​ -> ​ Int ​
​  editDistance stringA stringB
​  | ​ T ​.null stringA = ​ T ​.length stringB
​  | ​ T ​.null stringB = ​ T ​.length stringA
​  ​ -- ... ​

This rule is the base case of our recursive function, and it’s how we deal with situations where one string is longer than another. The rule works because, if the first string is empty, we need to add all of the letters from the second string. On the other hand, if the second string is empty, we need to remove all of the letters from the first string. In either case, that’s one edit per letter in the non-empty string.

Second, if the first letter of two strings are the same, then the edit distance is the distance between the remainder of the two strings:

​  editDistance :: ​ Text ​ -> ​ Text ​ -> ​ Int ​
​  editDistance stringA stringB
​  ​ -- ... ​
​  | ​ T ​.head stringA == ​ T ​.head stringB = editDistance restOfA restOfB
​  ​ -- ... ​
​  ​ where ​
​  restOfA = ​ T ​.tail stringA
​  restOfB = ​ T ​.tail stringB

In our implementation, we’re taking the tail of the two strings and calculating the distance between them recursively. This lets us step through the string and, as long as our values match, we never add any unnecessary edits.

The final rule says that if the first letters of our strings don’t match, we need to add one to the overall edit distance between the strings. Unlike our previous examples though, the recursive case isn’t quite so straightforward. Since we want to always return the minimum number of edits, we need to use the least expensive of our three options: inserting, deleting, or replacing a character.

​  editDistance :: ​ Text ​ -> ​ Text ​ -> ​ Int ​
​  editDistance stringA stringB
​  ​ -- ... ​
​  | otherwise = 1 + minimum [insertCost, deleteCost, swapCost]
​  ​ where ​
​  restOfA = ​ T ​.tail stringA
​  restOfB = ​ T ​.tail stringB
​  deleteCost = editDistance restOfA stringB
​  insertCost = editDistance stringA restOfB
​  swapCost = editDistance restOfA restOfB

We can figure out the costs of each approach by calculating the edit distance recursively. To find out the edit distance if we delete a character, we can drop the current character and recalculate the distance. Similarly, we can find the cost of inserting a character by removing a character from the target string, or the cost of replacing a character by dropping a character from both strings.

To help understand what’s going on, let’s step through a small example:

​  editDistance ​ "aaa" ​ ​ "abab" ​
​  | ​ T ​.head ​ "aaa" ​ == ​ T ​.head ​ "abab" ​ =
​  editDistance ​ "aa" ​ ​ "bab" ​
​  | otherwise = 1 + minimum [deleteCost, insertCost, swapCost]
​  = 1 + minimum [2, 1, 1]
​  = 1 + 1
​  = 2
​  ​ where ​
​  deleteCost = editDistance ​ "a" ​ ​ "bab" ​
​  | otherwise = 1 + minimum [deleteCost, insertCost, swapCost]
​  = 1 + minimum [3,1,2]
​  = 1 + 1
​  = 2
​  ​ where ​
​  deleteCost = editDistance ​ "" ​ ​ "bab" ​
​  | ​ T ​.null ​ "" ​ = ​ T ​.length ​ "bab" ​ = 3
​  insertCost = editDistance ​ "a" ​ ​ "ab" ​
​  | ​ T ​.head ​ "a" ​ == ​ T ​.head ​ "ab" ​ =
​  editDistance ​ "a" ​ ​ "b" ​
​  | otherwise = 1 + minimum [deleteCost, insertCost, swapCost]
​  = 1 + minimum [1, 1, 0]
​  = 1 + 0
​  = 1
​  ​ where ​
​  deleteCost = editDistance ​ "" ​ ​ "b" ​
​  | ​ T ​.null ​ "" ​ = ​ T ​.length ​ "b" ​ = 1
​  insertCost = editDistance ​ "a" ​ ​ "" ​
​  | ​ T ​.null ​ "" ​ = ​ T ​.length ​ "a" ​ = 1
​  swapCost = editDistance ​ "" ​ ​ "" ​
​  | ​ T ​.null ​ "" ​ = ​ T ​.length ​ "" ​ = 0
​  swapCost = editDistance ​ "" ​ ​ "ab" ​
​  | ​ T ​.null ​ "" ​ = ​ T ​.length ​ "ab" ​ = 2
​  insertCost = editDistance ​ "aa" ​ ​ "ab" ​
​  | ​ T ​.head ​ "aa" ​ == ​ T ​.head ​ "ab" ​ = editDistance ​ "a" ​ ​ "b" ​
​  | otherwise = 1 + minimum [deleteCost, insertCost, swapCost]
​  = 1 + minimum [1, 1, 0]
​  = 1 + 0
​  = 1
​  
​  
​  ​ where ​
​  deleteCost = editDistance ​ "" ​ ​ "b" ​
​  | ​ T ​.null ​ "" ​ = ​ T ​.length ​ "b" ​ = 1
​  insertCost = editDistance ​ "a" ​ ​ "" ​
​  | ​ T ​.null ​ "" ​ = ​ T ​.length ​ "a" ​ = 1
​  swapCost = editDistance ​ "" ​ ​ "" ​
​  | ​ T ​.null ​ "" ​ = ​ T ​.length ​ "" ​ = 0
​  swapCost = editDistance ​ "a" ​ ​ "ab" ​
​  | ​ T ​.head ​ "a" ​ == ​ T ​.head ​ "ab" ​ = editDistance ​ "" ​ ​ "b" ​
​  | ​ T ​.null ​ "" ​ = ​ T ​.length ​ "b" ​ = 1

The first thing we do in this example is strip off the leading “a” from both strings. Since they match, we know the distance between “aaa” and “abab” is going to be the same as the difference between “aa” and “bab”. Next, we have a mismatch between “a” and “b” so we need to decide whether the cheapest way forward is to

  • Delete “a” and add the distance from “a” to “bab”,
  • Insert the missing “b” and add the distance from “aa” to “ab”, or
  • Replace the “a” with “b” and add the distance from “a” to “ab”.

In the first branch, we try deleting the first “a”, but that puts us back into the same situation we just found ourselves in, with the remaining “a” not matching the initial “b” from “bab”. Once again we need to choose the smallest number of edits out of our three choices:

  • Delete the “a” and compare the empty string (“”) to “bab”.
  • Insert the missing “b“ and compare “a” to “ab”.
  • Replace the “a” with a “b” and compare the empty strings that are left.

This time, two of our branches, deletion and replacement, have empty strings and so they each end their recursion and give us back a value. We’ll need to take another trip through the code for this branch to find the difference between “a” and “ab”.

The recursion continues on for a while even with these relatively short strings. Before we move on with building our spellchecker, you should spend some more time with the example, and even walk through a few of your own examples. It will be helpful to have a good understanding of the mechanics of how the code works when we start to optimize it later in the chapter.

Spellchecking a Document

Now that we have a way to find the distance between two words, we can move on to spellchecking. The first thing we need to do is to decide on how we want to report a particular spelling suggestion back to the user. Let’s head over to the Types module in our library and create a new SuggestedMatch record to hold a suggestion. While we’re at it, let’s add a utility function called showSuggestedMatch that will format the suggestions nicely:

​  ​ {-# LANGUAGE RecordWildCards #-} ​
​  ​ module ​ ​ Types ​ ​ where ​
​  ​ import ​ ​ SpellCheck.Naive ​
​  ​ import ​ ​ Data.Text ​ (​ Text ​)
​  ​ import ​ ​ Text.Printf ​
​  
​  ​ data ​ ​ SuggestedMatch ​ = ​ SuggestedMatch ​
​  { matchWord :: ​ Text ​
​  , matchSearchedWord :: ​ Text ​
​  , matchDistance :: ​ Int ​
​  } ​ deriving ​ (​ Show ​, ​ Eq ​)
​  
​  showSuggestedMatch :: ​ SuggestedMatch ​ -> ​ String ​
​  showSuggestedMatch ​ SuggestedMatch ​{..} =
​  printf ​ "%s -> %s: %d" ​ matchWord matchSearchedWord matchDistance

Next, let’s head over to our top level SpellCheck and write a function that will spellcheck single words against a dictionary of words. We can start with a straightforward implementation:

​  ​ module ​ ​ SpellCheck ​ ​ where ​
​  ​ import ​ ​ SpellCheck.Types ​
​  ​ import ​ ​ SpellCheck.Naive ​
​  ​ import ​ ​ Data.Text ​ (​ Text ​)
​  
​  spellcheckWord :: [​ Text ​] -> ​ Text ​ -> [​ SuggestedMatch ​]
​  spellcheckWord dictionary word =
​  [ ​ SuggestedMatch ​ dictWord word (editDistance dictWord word)
​  | dictWord <- dictionary
​  ]

Running this version of our spellchecker in ghci will show us that we are in fact getting some recommendations for misspelled words:

​  λ dictionary = ["yellow", "mellow", "hello", "goodbye"]
​  λ printMatches = putStrLn . showSuggestedMatch
​  λ checkWord word = mapM_ printMatches $ spellcheckWord dictionary word
​  
​  λ checkWord "yello"
​  yellow -> yello: 1
​  mellow -> yello: 2
​  hello -> yello: 1
​  goodbye -> yello: 7
​  
​  λ checkWord "mello"
​  yellow -> mello: 2
​  mellow -> mello: 1
​  hello -> mello: 1
​  goodbye -> mello: 7
​  
​  λ checkWord "hello"
​  yellow -> hello: 2
​  mellow -> hello: 2
​  hello -> hello: 0
​  goodbye -> hello: 7

There are a couple of problems that we have right now. First, we’re showing suggestions for words that are many edits away. If someone typed “mello” it’s not very likely the word that they wanted was “goodbye”. We can fix this by adding a threshold so we can only show users words that are a close match. Second, we’re showing results for words that are correctly spelled. For our purposes, we only want to show suggestions for misspelled words, so if a word has an exact match in the dictionary we should avoid returning any suggestions for it.

Let’s refactor our spellchecker to take an extra parameter to configure how many edits are allowed for suggestions. While we’re at it, we’ll avoid returning any suggestions for correctly spelled words:

​  spellcheckWord :: [​ Text ​] -> ​ Int ​ -> ​ Text ​ -> [​ SuggestedMatch ​]
​  spellcheckWord dictionary threshold word =
​  getSuggestions dictionary ​ [] ​
​  ​ where ​
​  getSuggestions ​ [] ​ suggestions = suggestions
​  getSuggestions (dictWord:dict) suggestions
​  | distance == 0 = ​ [] ​
​  | distance > threshold = getSuggestions dict suggestions
​  | otherwise = getSuggestions dict (suggestion : suggestions)
​  ​ where ​
​  distance = editDistance dictWord word
​  suggestion = ​ SuggestedMatch ​ dictWord word distance

Let’s re-run this version of spellcheckWord with our same dictionary and test examples. We’ll use a threshold of 3. Most spellcheckers use a threshold of either 2 or 3. For all of the examples in this chapter, we’re going to use a threshold of 3. This will give us more results for each search, which in turn will give us more opportunities to identify and address performance problems in our code.

​  λ dictionary = ["yellow", "mellow", "hello", "goodbye"]
​  λ printMatches = putStrLn . showSuggestedMatch
​  λ checkWord word = mapM_ printMatches $ spellcheckWord dictionary 3 word
​  
​  λ checkWord "yello"
​  hello -> yello: 1
​  mellow -> yello: 2
​  yellow -> yello: 1
​  λ checkWord "mello"
​  hello -> mello: 1
​  mellow -> mello: 1
​  yellow -> mello: 2
​  λ checkWord "hello"

That looks much better! We’re only getting reasonable suggestions for our misspellings, and none at all for words that were spelled correctly.

The last feature we need to add to our SpellCheck.Naive module is a function to let us spellcheck an entire document. For most practical purposes, users will want to spellcheck an entire document for errors, rather than checking a word at a time. We’ll add a spellcheck function to let them do just that:

​  spellcheck :: [​ Text ​] -> ​ Int ​ -> [​ Text ​] -> [​ SuggestedMatch ​]
​  spellcheck dictionary threshold =
​  concatMap (spellcheckWord dictionary threshold)

Now that you’ve implemented the spellchecking module, you should update your project so that you can pass in some options and run the spellchecker from the command line. It will be important to build an executable that you can call outside of ghci since we’ll want to compile our program with optimizations and profile it to understand how to improve the performance.

For the examples in the rest of this chapter, we’ll assume a version of the application that takes four arguments: a dictionary of correctly spelled words, a document to spellcheck, an optional verbosity flag, and the name of the algorithm that we’re testing. You can customize the interface to your application however you like, but at a minimum you’ll likely find it helpful to add an argument to choose between different implementations of the spellchecker so that you can profile different approaches without having to recompile your program.

Profiling the Spellchecker

Now that we’ve built our application, let’s run it and see what kind of results we can get. A good place to start will be to take the test cases we were using manually in ghci and put those into files so that we can see how well our program runs.

Let’s create two files. First, we’ll create a dictionary of the words with correct spellings. In the examples we’ll call this small-dictionary.txt :

​  yellow
​  mellow
​  hello
​  goodbye

Next, let’s create a list of words we want to check. We’ll call this small-test-list.txt :

​  yello
​  mello
​  hello

Finally, let’s build the application and run it. We can use the time command to get a sense of how fast our program is running. Depending on your operating system, the output of time may look slightly different:

​  user@host$ time cabal exec spellcheck -- \
​  ./small-dictionary.txt ./small-test-list.txt verbose spellcheck-naive
​  hello -> yello: 1
​  mellow -> yello: 2
​  yellow -> yello: 1
​  hello -> mello: 1
​  mellow -> mello: 1
​  yellow -> mello: 2
​  
​  real 0m0.035s
​  user 0m0.020s
​  sys 0m0.007s

It looks like our application is running well enough that it’s hard to imagine what could be left to optimize. Unfortunately, these results are a bit misleading. We’re testing with a very small dictionary of words. If we want to implement a more complete spellchecking program, we’ll need to use a more complete dictionary.

There are several different free dictionaries available, and you may already have one installed on your operating system. The rest of the examples in this chapter will use the words.txt file from the Spell Checker Oriented Word List (SCOWL) [20] .

Preparing the Word List

| images/aside-icons/info.png | If you download the SCOWL word list, there’s some preparation work you should do before using the data in your programs. First, you’ll need to re-encode the wordlist to utf8. The word list shipped with SCOWL uses the ISO-8859 (extended Latin) encoding. You can convert the file to utf8 using the iconv tool.On Linux and WSL, you can convert the file by running iconv -t utf8 -o words.utf8 -f iso-8859-3 words.txt . The -o flag isn’t available on macOS, so instead you can redirect the output to a file: iconv -t utf8 -f iso-8859-3 words.txt > words.utf8Once you’ve converted the file to utf8, you should shuffle the contents of the file so they are no longer in alphabetical order. This will help us get more accurate data during our test. On all platforms, you can do this by typing sort -R words.utf8 > words.txt . |

Now that we have a complete dictionary, let’s create a new file named helllo.txt that holds a single typo, the word “helllo”:

​  helllo

After all of the setup, let’s test out our spellchecker on a larger list of words:

​  user@host$ time cabal exec spellcheck -- .\
​  /words.txt ./helllo.txt quiet spellcheck-naive
​  
​  found 173 suggested matches
​  
​  real 2m46.115s
​  user 2m46.032s
​  sys 0m0.076s

We found 173 suggestions, which is obviously quite a lot of options for a single typo. In a full-fledged spellchecking program we would apply some heuristics to limit the number of potential matches, but for the moment the larger number of results is less of a problem than the fact that our program took nearly three minutes to find suggestions for a single word! This is pretty unusable for a single word, let alone spellchecking a real document. We’ll need to do better.

If we want to improve the performance of our program, the first thing that we’ll need to do is start collecting data about where we’re spending our time. We can get that data by enabling profiling . We can enable profiling in our application by adding a cabal project file named cabal.project.local . Cabal project files give us a way to configure projects made up of one or more separate packages, and to configure them all together. They also offer a number of configuration options for tuning options like profiling for our packages. Let’s create a project file that will enable profiling for our application and library, and let’s pass in RTS options so we can collect profiling data when we run our program:

​  profiling: True
​  library-profiling: True
​  optimization: 2
​  
​  package *
​  ghc-options: -rtsopts -fprof-auto

The first part of our project file sets some global options:

  • profiling controls whether or not profiling is enabled for our executable. We need to enable this to collect profiling data when we run the program.

  • library-profiling enables us to collect profiling information from the library part of our project. Nearly all of our code lives in our library, so we need to turn this on to get useful data.

  • optimization sets the -O flag. We want our program to run fast, so we’re setting the optimization level to 2.

After setting our global options, we can also add some package-specific stanzas to our project file. You can have several of these stanzas that configure individual packages, several specific packages, or use a wildcard as we’ve done here. In this example, we’re setting passing a couple of flags to ghc :

  • -rtsopts will let us pass options to the runtime system, including options to configure profiling.

  • -fprof-auto will ask the compiler to automatically collect profile data from each function we define in our program. This is the most expensive profiling option, but also gives us the most detailed results.

Now that we’ve configured some profiling options, let’s recompile our program and then run it again:

​  user@host$ time cabal exec spellcheck -- \
​  ./words.txt ./helllo.txt quiet spellcheck-naive
​  
​  found 173 suggested matches
​  
​  real 10m59.992s
​  user 10m59.765s
​  sys 0m0.166s

Even though we haven’t actually turned on profiling for this particular run of our application, building our program with profiling enabled has caused a substantial impact on the performance of our application. Not all of the programs we run with profiling enabled will be slowed down so much, but collecting profiling data has exacerbated some of the inefficiencies that were already in our application. To get a look at what those are, let’s run our program again, and this time we’ll collect profiling data:

​  user@host$ time cabal exec spellcheck -- \
​  ./words.txt ./helllo.txt quiet spellcheck-naive +RTS -s -p
​  
​  found 173 suggested matches
​  2,448,464,651,528 bytes allocated in the heap
​  10,243,120 bytes copied during GC
​  12,391,304 bytes maximum residency (12 sample(s))
​  786,984 bytes maximum slop
​  37 MiB total memory in use (0 MB lost due to fragmentation)
​  
​  Tot time (elapsed) Avg pause Max pause
​  Gen 0 592385 colls, 0 par 1.784s 1.864s 0.0000s 0.0001s
​  Gen 1 12 colls, 0 par 0.021s 0.021s 0.0017s 0.0038s
​  
​  INIT time 0.000s ( 0.000s elapsed)
​  MUT time 652.690s (652.671s elapsed)
​  GC time 1.805s ( 1.885s elapsed)
​  RP time 0.000s ( 0.000s elapsed)
​  PROF time 0.000s ( 0.000s elapsed)
​  EXIT time 0.000s ( 0.000s elapsed)
​  Total time 654.495s (654.556s elapsed)
​  %GC time 0.0% (0.0% elapsed)
​  Alloc rate 3,751,342,896 bytes per MUT second
​  Productivity 99.7% of total user, 99.7% of total elapsed
​  
​  real 10m54.616s
​  user 10m53.895s
​  sys 0m0.653s

Thanks to the -s flag that we passed to the RTS, our program will print summary statistics about memory usage when it’s done running. You’ve already seen one example of using summary statistics when you learned about IORefs . In that chapter, we focused on the total memory usage of our application. In this case, the total memory usage might be a little high, but the overall number of bytes allocated and garbage collected is more interesting.

During the ten minutes our program was running, we allocated nearly 2.5 terabytes of memory. Haskell programs do tend to allocate a lot of memory, but that still seems unusually high. Summary statistics like these can sometimes help us identify unexpected space leaks, but in this case it doesn’t seem like we have enough information to entirely narrow down what’s happening, so let’s look at the actual profiling data that was generated.

When you run your program with the -p flag, your program will write profiling data to a file named <your-program-name>.prof . In this case, the file will be named spellcheck.prof .

Profiler Output Formatting

| images/aside-icons/info.png | The actual output generated by the profiler is too large to fit comfortably in this book. Instead, we will look at the format more generally and highlight particular sections of the profiler output. |

At the top of the profiling data, you’ll see a header that includes the time the program was run, what arguments were passed to it, and the total amount of time and memory that it used:

​  Tue May 31 01:41 2022 Time and Allocation Profiling Report (Final)
​  
​  spellcheck +RTS -s -p -RTS ./words.txt ./helllo.txt quiet spellcheck-naive
​  
​  total time = 681.24 secs (681243 ticks @ 1000 us, 1 processor)
​  total alloc = 1,536,053,166,248 bytes (excludes profiling overheads)

This gives you a high-level overview of the run of your application. It’s not particularly useful for diagnosing a performance problem, but as you are working on different implementations of some code, you’ll frequently accumulate many different profiling files that you want to compare. Having a header to quickly glance at to see what version of the program you ran, and how well it performed, can make it much easier to sort through several profiling files.

The next section of the profiling output shows you the most expensive parts of your program. There are five columns:

  • COST CENTER : Cost centers are names assigned to a particular part of the code that we want to measure when we’re profiling. Since we used -fprof-auto , the compiler automatically created a cost center for all of our functions. You’ll notice that for things like deleteCost and insertCost , which are where bindings inside of editDistance , the cost center includes the top-level function as well as the name of the particular binding.

  • MODULE : This is the module where the code is defined.

  • SRC : This is the source file where the code is defined.

  • %time : This field tells us what percent of the overall program runtime was spent inside of this particular cost center. For example, we can see that we spent 54 percent of our time in editDistance .

  • %alloc : Similar to %time, this field tells us what percentage of memory allocations were done inside of a particular cost center. We can see here that while we only spent about half of our time in editDistance it was responsible for nearly 80 percent of the memory our program allocated.

In our example, the five most expensive cost centers are:

cost center %time % alloc
editDistance 54.2 78.2
editDistance.deleteCost 16.1 5.3
editDistance.swapCost 14.9 5.3
editDistance.insertCost 10.1 0.0
editDistance.restOfA 4.5 11.1

The most expensive of these cost centers is editDistance , which takes up about half of the time and about 80 percent of the allocations in our program. The rest of the cost centers are all where bindings that were defined inside of editDistance . When we enabled -fprof-auto to ask the compiler to insert cost centers for us, it added them to all of the let and where bindings in our program, so we can narrow down the costs to particular parts of a larger function.

Overall, the top cost centers are exactly what we’d expect from our application; almost all of the time and memory is being spent in the function that is doing almost all of the work. We still don’t have a good explanation for why our program is so slow. Let’s move a bit further down the file and look at the detailed profiling output.

The detailed output has a lot of the same information that was in our high level summary. We have the name of each cost center, along with the source file and module it’s in, and a numeric identifier. We also now have two different pairs of time and allocation fields. The first pair of fields, labeled individual , tells us about the time and allocations in that particular cost center. The second pair of fields, labeled inherited , tell us how much time and memory were used by that function and all of its children in the call tree. The inherited cost can be a good way to spot functions that call several functions that don’t individually cost very much, but cumulatively end up having a big performance impact.

Finally, the entries field is the field that will be most interesting to us right now. This field tells us how many times a particular cost center was entered—in other words, how many times a particular function was called, or a value was evaluated. Let’s look at the profiling data, starting with the call to spellcheckWord in our profiler output, and see what it can tell us. The output here has been reformatted to make it easier to follow:

​  spellcheckWord
​  entries: 1
​  (individual) %time: 0.0, %alloc: 0.0
​  (inherited) %time: 100.0, %alloc: 100.0
​  
​  spellcheckWord.getSuggestions
​  entries: 123383
​  (individual) %time: 0.0, %alloc: 0.0
​  (inherited) %time: 100.0, %alloc: 100.0
​  
​  
​  spellcheckWord.getSuggestions.distance
​  entries: 123382
​  (individual) %time: 0.0 %alloc: 0.0
​  (inherited) %time: 100.0 %alloc: 100.0
​  
​  editDistance
​  entries: 15590594654
​  (individual) %time: 54.2, %alloc: 78.2
​  (inherited) %time: 100.0 %alloc: 100.0
​  
​  editDistance.restOfA
​  entries: 5337541962
​  (individual): %time: 4.6 %alloc: 11.1
​  (inherited): %time: 4.6 %alloc: 11.1
​  
​  editDistance.restOfB
​  entries: 5337541962
​  (individual): %time: 0.1 %alloc: 0.0
​  (inherited): %time: 0.1 %alloc: 0.0
​  
​  editDistance.deleteCost
​  entries: 5126464655
​  (individual): %time: 15.9 %alloc: 5.3
​  (inherited): %time: 15.9 %alloc: 5.3
​  
​  editDistance.insertCost
​  entries: 5126464655
​  (individual): %time: 10.1 %alloc: 0.0
​  (inherited): %time: 10.1 %alloc: 0.0
​  
​  editDistance.swapCost
​  entries: 5126464655
​  (individual): %time: 15.1 %alloc: 5.3
​  (inherited): %time: 15.1 %alloc: 5.3

We can see from the profiling data that spellcheckWord is called just once. This is what we’d expect since our input file only contains a single word we want to spellcheck. Next, spellcheckWord.getSuggestions is called 123383 times. This matches the number of words in the SCOWL words corpus, so we can see it’s also being called once for each of the dictionary words we’re checking our single input word against. Similarly, spellcheckWord.getSuggestions.distance is also called 123383 times—again once per word in our dictionary. So far so good, but editDistance is being called an astounding 15590594654 times. That works out to almost 126359 calls per dictionary word! We might have expected our naive algorithm to do a bit of re-work, but the profiler is telling us the inefficiency of our algorithm is much worse than we might have expected. Let’s go back to the algorithmic drawing board and see if we can improve our performance.

Over the next few sections, we’ll look at several alternate ways we can avoid doing extra work and incrementally improve the performance of our algorithm.