

Stingier: producing a program that gobbles less heap space

"I think I have a space leak..." Re-run your program with `+RTS -Sstderr', and remove all doubt! (You'll see the heap usage get bigger and bigger...) [Hmmm... this might be even easier with the `-F2s' RTS option; so... `./a.out +RTS -Sstderr -F2s'...]

Once again, the profiling facilities (section See section Profiling Haskell programs) are the basic tool for demystifying the space behaviour of your program.

Strict functions are good to space usage, as they are for time, as discussed in the previous section. Strict functions get right down to business, rather than filling up the heap with closures (the system's notes to itself about how to evaluate something, should it eventually be required).

If you have a true blue "space leak" (your program keeps gobbling up memory and never "lets go"), then 7 times out of 10 the problem is related to a CAF (constant applicative form). Real people call them "top-level values that aren't functions." Thus, for example:

x = (1 :: Int)
f y = x
ones = [ 1, (1 :: Float), .. ]
`x' and `ones' are CAFs; `f' is not.

The GHC garbage collectors are not clever about CAFs. The part of the heap reachable from a CAF is never collected. In the case of `ones' in the example above, it's disastrous. For this reason, the GHC "simplifier" tries hard to avoid creating CAFs, but it cannot subvert the will of a determined CAF-writing programmer (as in the case above).
