So far in this chapter we’ve improved the implementation of our code by making changes to the algorithms and underlying data structures that we’re using. Algorithms and data structures are always a good place to start when we need to make our programs more efficient, but once we’ve addressed those opportunities we can often still realize significant performance improvements by making use of micro-optimizations. These are optimizations that tend to have a small individual impact, but can add up collectively. In this section, we’ll look at a version of the editDistance function that has had several different micro-optimizations applied. Before we look at the code though, let’s take a moment to review the progress that we’ve made in optimizing our application, and see what we have to look forward to with this version:
| Version | Runtime | Allocations |
|---|---|---|
| Naive | 680.0s | 1500 GB |
| List Memo | 1.3s | 2.6 GB |
| Vector Memo | 0.5s | 1.0 GB |
| Micro-Optimized | 0.05s | 0.1 GB |
As you can see, the most substantial improvement by far came from using a better algorithm, but we have still gotten nearly an order of magnitude improvement in performance by adding the micro-optimizations we’ll be looking at in this section. So, let’s take a look at the implementation:
| | {-# LANGUAGE BangPatterns #-} |
| | module SpellCheck.LowLevelUnboxed where |
| | import Data.Text ( Text ) |
| | import qualified Data.Text as T |
| | import qualified Data.Text.Unsafe as TU |
| | import Types |
| | import Prelude hiding ( length , read , words ) |
| | import Data.Foldable ( for_ ) |
| | import Control.Monad.ST |
| | import qualified Data.Vector.Unboxed.Mutable as MVec |
| | |
| | {-# INLINE editDistance #-} |
| | editDistance :: Text -> Text -> Int |
| | editDistance stringA stringB = runST $ do |
| | let |
| | aLen = T .length stringA |
| | bLen = T .length stringB |
| | {-# INLINE lookupIndex #-} |
| | 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 |
| | let |
| | columnCost !idxA !textIdxA |
| | | idxA > aLen = pure () |
| | | otherwise = do |
| | let |
| | ( TU . Iter !a' !textIdxA') = TU .iter stringA textIdxA |
| | {-# INLINE rowCost #-} |
| | rowCost !idxB !textIdxB |
| | | idxB > bLen = pure () |
| | | otherwise = do |
| | let |
| | ( TU . Iter !b' !textIdxB') = TU .iter stringB textIdxB |
| | cost = if a' == b' 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)) |
| | let |
| | {-# INLINE newCost #-} |
| | newCost = min swapCost $ min insertCost deleteCost |
| | MVec .write cache (lookupIndex idxA idxB) newCost |
| | rowCost (idxB + 1) (textIdxB + textIdxB') |
| | rowCost 1 0 |
| | columnCost (idxA + 1) (textIdxA + textIdxA') |
| | columnCost 1 0 |
| | MVec .read cache (lookupIndex aLen bLen) |
Inlining (0.60s Saved)
The first major change you might notice in this version of our code is the judicious use of inlining. If you aren’t familiar with it, inlining is a common technique used by compilers, including GHC, to transform code that calls a function with code that directly implements the body of that function. For example, say we have a pair of functions, addTwo and addFour :
| | addTwo a b = a + b |
| | addFour a b c d = addTwo a b + addTwo c d |
If we chose to inline addTwo , the compiler would replace calls with the actual function body, giving us:
| | addFour a b c d = a + b + c + d |
The choice to inline a particular piece of code or not is ultimately made by GHC, but when necessary we can make strong suggestions to the compiler about code that it might want to consider inlining (or not inlining). As you may have noticed in our example code, we can use the INLINE pragma to suggest to the compiler that it should consider trying to inline a particular piece of code if it can.
| Suggesting and Allowing Inlining |
|---|
|
| When optimizations are enabled, GHC will try to make good choices about when to inline code within a single module. The INLINE pragma is a strong suggestion to the compiler that it should try to inline a particular function, both within the current module and when it’s called from other modules. The INLINABLE pragma is similar, but a bit weaker. It tells the compiler to provide all the necessary information so that a function can be inlined outside of the module where it was defined, but it doesn’t encourage the compiler to make any particular choice about whether to inline or not. |
Inlining by itself isn’t actually an optimization. Inlining can make your programs take longer to compile, and sometimes it can even make them less efficient. If the compiler has made a poor decision and tried to inline something it shouldn’t have, you can persuade it of that by using the NOINLINE pragma.
Inlining can be quite helpful at getting the compiler to generate more efficient code for us. That’s not because inlining is directly improving the code, but the process of inlining code can help the compiler uncover opportunities to apply other optimizations.
In our highly optimized edit distance function, we’re inlining four functions. First, we’re inlining editDistance itself. Second, we’re inlining lookupIndex , which helps us find the offsets into the vector that we want to use when looking up cached edit distances, or setting the edit distance for our current part of the loop. Third, we’re inlining the rowCost function, which is the innermost part of our edit distance loop. Finally, we’re inlining the newCost binding that is used to find the actual minimum edit cost for the particular point in our string.
Why these particular examples and not some others? In general, the choice to inline some code or not lends itself better to profiling than thinking through the code and trying to make an informed decision, but in our case there are a couple of factors that make inlining worth the attempt. First, when we have tight inner loops we may find that inlining can help the compiler generate more efficient code by reducing the overhead of making a function call. In most cases, the overhead of calling a function is small enough to be irrelevant, but it can add up in very performance critical code. Second, when we’re dealing with data-structure-heavy code, for example the lists and vectors that are at the core of our edit distance implementation, we want to give the compiler the opportunity to perform fusion . Fusion is an optimization technique where the compiler can remove intermediate stages of a series of transformations on a data structure. The most well-known example of this is calling map on lists. Imagine you have some inefficient code like this:
| | inefficient = map a . map b . map c $ someList |
Without fusion, each call to map would allocate a new list and walk the entire list applying the function. With fusion, the compiler can rewrite the expression to:
| | inefficient = map (a . b. c) someList |
In spite of the name, this version is much more efficient because it doesn’t need to allocate any intermediate lists, and only needs to walk the length of the list a single time.
There are many other optimizations that GHC can do, and exhaustively listing them is outside of scope of this book, but many of them can be enabled in some cases through inlining.
Bang Patterns (0.05s Saved)
The second small optimization that we’ve done is enable the BangPatterns language extension and use it to make many of the parameters in our inner loop strict. You’ve already seen some examples earlier in this book of how we can improve performance and memory usage by forcing certain values to be evaluated strictly.
Avoiding Allocations with Unsafe Text (0.30s Saved)
The third notable change to this edit distance implementation is that we’ve moved away from unpacking or indexing into our strings. Instead, we’re using the ominously named Data.Text.Unsafe module from the text package to directly iterate through the underlying text representation. As with most other examples of highly optimized code, this example trades off some amount of safety and ease of use for raw performance by using a library that does away with many of the conveniences of higher-level access to Text data. By directly iterating through the Text values, we’ve avoided having to traverse the string an extra time to unpack it, and we’ve avoided the overhead of allocating an additional data structure to keep track of the character data.
Unboxed Values (0.25s Saved)
Most Haskell values are boxed values. That is to say, a Haskell value is a thunk that, when evaluated, will reference some particular value in memory. Boxed values in Haskell can be lazily evaluated, and they can be undefined . For all of their convenience, they also come with the overhead of having to allocate extra memory to hold the reference to the underlying value, as well as the computational cost of following an extra layer of indirection when we want to access the value being referenced. When we’re dealing with performance critical code, it’s often beneficial to work with raw machine values instead of references to values. In that case, we can benefit from unboxed values.
Unboxed values are raw machine values, like words, ints, and doubles. GHC provides us with a low-level interface to working with unboxed values through the GHC.Exts module in base , but working with unboxed values this way can be quite challenging. Thankfully, unboxed vectors provide us with a fast and efficient way to deal with unboxed values with relatively low overhead, especially when we’re dealing with collections of unboxed values.
The last major performance improvement we’ve added to our edit distance application is to change our import of Data.Vector.Mutable to Data.Vector.Unboxed.Mutable . You’ll notice that nothing else in our implementation needed to change, and you can freely swap between the boxed and unboxed versions locally if you want to look at the performance characteristics of each approach.