man haskell/laziness
Laziness in practice: foldl, foldl' and thunks
Why can foldl (+) 0 over ten million numbers need 600 MB of memory, and why
does the same line need almost none once you compile with -O2?
main :: IO ()
main = print (foldl (+) 0 [1 .. 10000000 :: Int])
Haskell evaluates an expression only when its value is needed. Until then the
expression is stored as a thunk: a heap object that holds the code and the
free variables to compute the value later. That is cheap for one value. It
gets expensive when a program builds a long chain of thunks that nothing
forces until the end. This article looks at three places where that happens or
doesn’t (left folds, values stored in a map, and sorting) with the source of
GHC 9.14.1’s base and containers 0.8 and measurements on an Apple M2 Pro.
The short version
foldl builds one thunk per element and evaluates them all at the end.
foldl' forces the accumulator at every step. With -O2, GHC’s strictness
analysis usually turns foldl into foldl' on its own, so the difference
only shows without optimisation. Values stored inside a lazy data structure,
like Data.Map, are out of the analysis’ reach, and there you choose
Data.Map.Strict. And laziness can also save work, as take 3 of a sorted
list shows.
What foldl builds
Both left folds are defined in GHC.Internal.List on top of foldr, so that
they can take part in list fusion
(List.hs L349-L352,
L395-L398):
foldl k z0 xs =
foldr (\(v::a) (fn::b->b) -> oneShot (\(z::b) -> fn (k z v))) (id :: b -> b) xs z0
foldl' k z0 = \xs ->
foldr (\(v::a) (fn::b->b) -> oneShot (\(z::b) -> z `seq` fn (k z v))) (id :: b -> b) xs z0
The only difference is z `seq`. seq evaluates its first argument before
returning the second. Without it, each step passes k z v along unevaluated,
and the accumulator grows into a nested expression:
foldl (+) 0 [1, 2, 3, 4]
z0 = 0
z1 = 0 + 1 (thunk)
z2 = z1 + 2 (thunk pointing at z1)
z3 = z2 + 3 (thunk pointing at z2)
z4 = z3 + 4 (thunk pointing at z3) <- returned, then forced:
z4 needs z3, needs z2, ...
With ten million elements that is ten million thunks on the heap before the
first addition happens, and forcing them recurses ten million levels deep.
foldl' evaluates z1 before it builds the next step, so only one number is
ever live.
Measuring it
This program sums ten million Ints with either fold:
import Data.List (foldl')
import System.Environment (getArgs)
main :: IO ()
main = do
[which, n] <- getArgs
let xs = [1 .. read n] :: [Int]
case which of
"foldl" -> print (foldl (+) 0 xs)
"foldl'" -> print (foldl' (+) 0 xs)
_ -> error "foldl or foldl'"
I compiled it three ways. -rtsopts lets the binary accept +RTS -s, which
prints memory and GC statistics at exit; grep keeps the peak memory and the
total time.
$ ghc -O0 -rtsopts -v0 -o sum-O0 sum.hs
$ ghc -O2 -rtsopts -v0 -o sum-O2 sum.hs
$ ghc -O2 -fno-strictness -rtsopts -v0 -o sum-nostrict sum.hs
$ ./sum-O0 foldl 10000000 +RTS -s 2>&1 | grep -E 'residency|Total'
619,453,504 bytes maximum residency (9 sample(s))
Total time 1.399s ( 1.403s elapsed)
$ ./sum-O0 "foldl'" 10000000 +RTS -s 2>&1 | grep -E 'residency|Total'
44,328 bytes maximum residency (2 sample(s))
Total time 0.060s ( 0.075s elapsed)
$ ./sum-O2 foldl 10000000 +RTS -s 2>&1 | grep -E 'residency|Total'
44,328 bytes maximum residency (2 sample(s))
Total time 0.050s ( 0.060s elapsed)
$ ./sum-O2 "foldl'" 10000000 +RTS -s 2>&1 | grep -E 'residency|Total'
44,328 bytes maximum residency (2 sample(s))
Total time 0.047s ( 0.059s elapsed)
$ ./sum-nostrict foldl 10000000 +RTS -s 2>&1 | grep -E 'residency|Total'
603,996,416 bytes maximum residency (9 sample(s))
Total time 1.201s ( 1.243s elapsed)
$ ./sum-nostrict "foldl'" 10000000 +RTS -s 2>&1 | grep -E 'residency|Total'
44,328 bytes maximum residency (2 sample(s))
Total time 0.074s ( 0.075s elapsed)
At -O0 the lazy fold holds 619 MB at its peak and takes 23 times as long as
foldl'. At -O2 the two are the same. The -fno-strictness build shows
what rescued it. -fstrictness is on by default with -O, and the user guide
describes it as demand analysis, saying “If an argument is scrutinised on every code
path, the function is strict in that argument and GHC is free to use the more
efficient call-by-value calling convention”. With the analysis turned off,
foldl is back at 604 MB.
foldl’ stops at the outermost constructor
seq evaluates to weak head normal form: the outermost constructor, nothing
inside it. A fold whose accumulator is a pair is “strict” only in the pair:
{-# LANGUAGE BangPatterns #-}
import Data.List (foldl')
import System.Environment (getArgs)
main :: IO ()
main = do
[which] <- getArgs
let xs = [1 .. 10000000] :: [Int]
(s, c) = case which of
"pair" -> foldl' (\(s0, c0) x -> (s0 + x, c0 + 1)) (0, 0) xs
"bang" -> foldl' (\(!s0, !c0) x -> (s0 + x, c0 + 1)) (0, 0) xs
_ -> error "pair or bang"
print (s `div` c)
$ ghc -O0 -rtsopts -v0 -o mean-O0 mean.hs
$ ghc -O2 -rtsopts -v0 -o mean-O2 mean.hs
$ ./mean-O0 pair +RTS -s 2>&1 | grep -E 'residency|Total'
729,580,040 bytes maximum residency (10 sample(s))
Total time 2.068s ( 2.071s elapsed)
$ ./mean-O0 bang +RTS -s 2>&1 | grep -E 'residency|Total'
44,328 bytes maximum residency (2 sample(s))
Total time 0.199s ( 0.199s elapsed)
$ ./mean-O2 pair +RTS -s 2>&1 | grep -E 'residency|Total'
44,328 bytes maximum residency (1 sample(s))
Total time 0.010s ( 0.010s elapsed)
$ ./mean-O2 bang +RTS -s 2>&1 | grep -E 'residency|Total'
44,328 bytes maximum residency (1 sample(s))
Total time 0.009s ( 0.015s elapsed)
The pair version uses foldl' and still builds two chains of thunks inside
the pair. The bang patterns force both fields every time the lambda takes
the pair apart. Again -O2 hides the problem. With optimisation on, the pair
version needs no more memory than the bang version.
Thunks inside a data structure
The analysis works on function arguments and local bindings. It can’t decide
that a value stored in a lazy field of a constructor will be needed, so
whatever you put there stays a thunk. Data.Map’s node has exactly such a
field, the value
(Map/Internal.hs L473):
data Map k a = Bin {-# UNPACK #-} !Size !k a !(Map k a) !(Map k a)
| Tip
!k is strict, a is not. The lazy insertWith stores f x y in that field
without evaluating it, and its source comment admits it “always changes the
tree, either adding a new entry or replacing an element with a thunk”
(L866-L881).
GHCi’s :sprint prints a value without forcing it, and shows each thunk as
_. This GHCi script counts the list [3, 1, 3, 2, 3] with both modules and
asks each map for its size, which forces the tree but none of the values:
import qualified Data.Map as Lazy
import qualified Data.Map.Strict as Strict
let xs = [3, 1, 3, 2, 3] :: [Int]
let lazyCounts = Lazy.fromListWith (+) [(x, 1 :: Int) | x <- xs]
let strictCounts = Strict.fromListWith (+) [(x, 1 :: Int) | x <- xs]
Lazy.size lazyCounts
Strict.size strictCounts
:sprint lazyCounts
:sprint strictCounts
$ ghci -v0 < sprint.ghci
3
3
lazyCounts = Data.Map.Internal.Bin
3 2 1
(Data.Map.Internal.Bin
1 1 1 Data.Map.Internal.Tip Data.Map.Internal.Tip)
(Data.Map.Internal.Bin
1 3 _ Data.Map.Internal.Tip Data.Map.Internal.Tip)
strictCounts = Data.Map.Internal.Bin
3 2 1
(Data.Map.Internal.Bin
1 1 1 Data.Map.Internal.Tip Data.Map.Internal.Tip)
(Data.Map.Internal.Bin
1 3 3 Data.Map.Internal.Tip Data.Map.Internal.Tip)
Each Bin prints as size, key, value, left, right. Keys 1 and 2 were inserted
once, and their value is the literal 1. Key 3 was inserted three times, and in
the lazy map its count is _, an unevaluated 1 + (1 + 1). The strict map
holds 3. Data.Map.Strict.insertWith differs from the lazy one by a single
bang, EQ -> let !y' = f x y in Bin sy kx y' l r
(Strict/Internal.hs L493-L503).
At scale, this program counts a million numbers into ten keys, so every key collects a chain of 100,000 additions in the lazy map:
import qualified Data.Map as Lazy
import qualified Data.Map.Strict as Strict
import System.Environment (getArgs)
main :: IO ()
main = do
[which] <- getArgs
let xs = [i `mod` 10 | i <- [1 .. 1000000]] :: [Int]
case which of
"lazy" -> print (Lazy.toList (Lazy.fromListWith (+) [(x, 1 :: Int) | x <- xs]))
"strict" -> print (Strict.toList (Strict.fromListWith (+) [(x, 1 :: Int) | x <- xs]))
_ -> error "lazy or strict"
$ ghc -O0 -rtsopts -v0 -o count-O0 count.hs
$ ghc -O2 -rtsopts -v0 -o count-O2 count.hs
$ ./count-O0 lazy +RTS -s 2>&1 | grep -E 'copied|residency|Total'
159,852,752 bytes copied during GC
32,518,488 bytes maximum residency (7 sample(s))
Total time 0.170s ( 0.181s elapsed)
$ ./count-O0 strict +RTS -s 2>&1 | grep -E 'copied|residency|Total'
83,080 bytes copied during GC
44,328 bytes maximum residency (2 sample(s))
Total time 0.055s ( 0.060s elapsed)
$ ./count-O2 lazy +RTS -s 2>&1 | grep -E 'copied|residency|Total'
150,158,848 bytes copied during GC
23,361,696 bytes maximum residency (9 sample(s))
Total time 0.135s ( 0.150s elapsed)
$ ./count-O2 strict +RTS -s 2>&1 | grep -E 'copied|residency|Total'
434,192 bytes copied during GC
44,328 bytes maximum residency (2 sample(s))
Total time 0.018s ( 0.030s elapsed)
This time -O2 doesn’t help. The lazy map still peaks at 23 MB and takes
about 7 times as long as the strict one. The fix is a choice of module, and the
strict module states its rule in its header, that “If all values stored in all
maps in the arguments are in WHNF, then all values stored in all maps in the
results will be in WHNF once those maps are evaluated”
(Strict.hs L22-L31).
That is WHNF again, so a Map k (Int, Int) from the strict module still
holds lazy Ints inside its pairs.
Laziness that saves work: take 3 of a sort
Data.List.sortBy is a merge sort
(OldList.hs L1619-L1723).
It first splits the input into runs that are already ascending or strictly
descending (a descending run is reversed, and “strictly” keeps equal elements
in input order, which is what makes the sort stable). Then it merges the runs
in rounds, four at a time where it can. Every merge is lazy. It produces the
smaller head and leaves the rest of its output as a thunk. So the first
element of the sorted list costs one pass to find the runs plus one comparison
per merge, and each further element costs one comparison per level of
merging.
To count comparisons, this program wraps compare in a counter:
import Data.IORef
import Data.List (sortBy)
import System.IO.Unsafe (unsafePerformIO)
import System.Environment (getArgs)
counter :: IORef Int
counter = unsafePerformIO (newIORef 0)
{-# NOINLINE counter #-}
-- compare, but count every call
countingCompare :: Int -> Int -> Ordering
countingCompare a b = unsafePerformIO $ do
modifyIORef' counter (+ 1)
return (compare a b)
{-# NOINLINE countingCompare #-}
-- a fixed pseudo-random permutation-ish list
pseudo :: Int -> [Int]
pseudo k = take k (drop 1 (iterate (\x -> (x * 1103515245 + 12345) `mod` 2147483648) 42))
main :: IO ()
main = do
[k] <- map read <$> getArgs
let xs = pseudo k
print (sum xs) -- build the list before counting
writeIORef counter 0
print (take 3 (sortBy countingCompare xs))
readIORef counter >>= \c -> putStrLn ("take 3: " ++ show c ++ " comparisons")
writeIORef counter 0
print (sum (sortBy countingCompare xs))
readIORef counter >>= \c -> putStrLn ("whole sort: " ++ show c ++ " comparisons")
$ ghc -O0 cmpcount.hs
$ ./cmpcount 10000 | grep comparisons
take 3: 14162 comparisons
whole sort: 124991 comparisons
$ ./cmpcount 100000 | grep comparisons
take 3: 141431 comparisons
whole sort: 1599993 comparisons
$ ./cmpcount 1000000 | grep comparisons
take 3: 1413267 comparisons
whole sort: 19166644 comparisons
take 3 . sortBy makes about 1.41 comparisons per element at every size. That
grows linearly, like a hand-written loop that keeps the three smallest. The
full sort makes about n log2 n. In a strict language the same line would sort
everything and then throw almost all of it away.
Curious facts
sumandproducton lists arefoldl' (+) 0andfoldl' (*) 1(List.hs L480-L498). They used to be lazy folds; the base changelog lists the switch to strict folds in 4.16.0.0.- The default
foldl'of theFoldableclass carries a comment that it now forces “the accumulatorzrather than the value computed by the operatork, this matches the documented strictness” (Foldable.hs L358-L366). foldlis written withfoldrand aoneShothint. The note next to it says this “is only a good idea if the compiler can optimize the resulting code”, and relies on call arity analysis or theoneShotannotation to turn it back into a loop (List.hs L355-L367).sortOn fstores eachf xin a pair and forces it withseqbefore sorting, so the key is computed once per element. Its documentation still recommendssortBy (comparing f)“for trivial projections” (OldList.hs L1851-L1868).- Since base 4.21,
sortcompares with(>)instead ofcompare, and the changelog warns that this “may break malformedOrdinstances”.
History
- containers 0.5.0.0 (May 2012, GHC 7.6.1):
Data.Map.StrictandData.Map.Lazyreplace strict functions named with an apostrophe. The changelog callsinsertWithinstead ofinsertWith'“a common source of containers-related performance bugs”. - base 4.15.0.0 (GHC 9.0.1): the
Foldablemethodssum,product,maximumandminimumbecome stricter by default. - base 4.16.0.0 (GHC 9.2.1):
sum,product,maximumandminimuminGHC.Listare implemented with strict folds. - base 4.20.0.0 (GHC 9.10.1):
Preludeexportsfoldl', so it no longer needs an import fromData.List. - base 4.21.0.0 (GHC 9.12.1):
sortgets the improved merging strategy (“four-way merge” in the source comment, GHC issue 24280).
Sources
libraries/ghc-internal/src/GHC/Internal/List.hsat ghc-9.14.1-release:foldl, Note Left folds via right fold,foldl',sumandproductGHC/Internal/Data/Foldable.hsfoldl'GHC/Internal/Data/OldList.hsat ghc-9.14.1-release:sort,sortByand the merge sort,sortOn- base changelog at ghc-9.14.1-release (entries for 4.15, 4.16, 4.20, 4.21)
- containers v0.8:
Data.Map.InternalMap, lazyinsertWith, strictinsertWith,Data.Map.Strictheader, changelog - GHC 9.14.1 user guide:
-fstrictnessand:sprint
grep -rl /lib/haskell/laziness/
ls haskell/
- draft Data.Map is a tree: how Haskell's containers workWhat containers 0.8 does with your keys: a weight-balanced binary tree for Data.Map, a big-endian Patricia trie for Data.IntMap, path copying on every insert, and how deep the trees really get.