[Haskell-cafe] Space leaks (was: How do I get a long iteration to run in constant space)

Graham Klyne GK at ninebynine.org
Tue Oct 5 05:26:10 EDT 2004

I've been starting to take note of discussion about space leaks in 
Haskell.  So far, it's not a topic that's bothered me, other than obvious 
programming errors, and I've never found the need to force strict 
evaluation of my Haskell programs.  I find myself wondering why this is.

Your comment about arithmetic expressions is telling:  the kind of program 
I have been writing (parsers, symbolic processing, etc.) performs almost no 
arithmetic.  (So far, I've used lists instead of arrays, so a usual source 
of arithmetic functions is missing.)

I've also worked with datasets that fit in memory, so failure to "stream" 
data hasn't been a problem.  I suspect that's the more pernicious case for 
space leaks, since the causes aren't always so obvious.

Are there any guidelines or warning signs to look out for that may be 
indicative of potential space-leak problems?  So far, I can think of:
- arithmetic results
- multiple uses of a large data value


At 00:44 05/10/04 -0700, oleg at pobox.com wrote:

>I added two lines to your code:
>iterate2 f x n | seq f $ seq x $ seq n $ False = undefined
>iterate2 f x n = --- as before
>rk4Next f h (x, y) | seq f $ seq h $ seq x $ seq y $ False = undefined
>rk4Next f h (x, y) = -- as before
>I also increased ten times the number of steps for the last iteration,
>to make the example more illustrative.
>    putStr (show (rk4 stiff 0 1 (exp (-1)) 1000000))
>The rest of the code is unchanged. The program now runs on GHCi
>*Foo> main
>on on hugs
>with the default stack size for both interpreters. It seems the code
>does run in constant space now.
>The added lines are meant to turn the relevant functions from lazy to
>strict. When you see something like '(n-1)' and 'y + a1/6', it is a
>red flag. These are exactly the kinds of expressions that lead to
>memory exhaustion. Perhaps it is because the size of an unevaluated
>thunk for (n-1) is so much bigger than the size of the evaluated
>thunk. It seems that arithmetic expressions are the best candidates
>for some opportunistic evaluation...
>Haskell-Cafe mailing list
>Haskell-Cafe at haskell.org

Graham Klyne
For email:

More information about the Haskell-Cafe mailing list