[racket] Understanding GC when working with streams

From: Konrad Hinsen (konrad.hinsen at fastmail.net)
Date: Sat Sep 7 06:16:45 EDT 2013

Lawrence Woodman writes:

 >   i.  Why does the GC seem to collect more effectively when the stream is
 >       created in a function as opposed to in a straight definition? i.e
 >       test-gen-filtered-nums? passes, although I note that
 >       test-for/sum-gen-filtered-nums? doesn't.

I don't know much about the internals of Racket, but for this one I have
a strong suspicion: The definitions

  (define nums (in-range max-num))
  (define filtered-nums
    (stream-filter (λ (i) (values #t)) nums))

don't allow the garbage collector to ever reclaim the storage occupied
by the streams, because you could at any time traverse them again.

Streams are conceptually handled like lists with a head and a tail,
except that the tail is a thunk of code that is evaluated when needed.
When you create a stream and walk through it, the heads can be
discarded as they are handled. But if you keep a reference to the head
of the whole stream, everything has to remain in memory.

Konrad.


Posted on the users mailing list.