On 3/17/06, Toby DiPasquale <toby / cbcg.net> wrote:
> I am in the middle of writing some code that will exist as a
> long-running process on a number of machines. I am having trouble
> keeping memory utilization down, which is important in this case,
[snip]
> source code, anything really that will help me better understand how to
> write Ruby code that doesn't "leak" and can be sustained as a
> long-running process without an ever-increasing memory footprint?
>
> Any help would be greatly appreciated. Thanks in advance.

Maybe you already knew this stuff, but, here's some things that might help you:

Set things to nil after you're finished using them.

Avoid continuations. If I recall correctly, the GC doesn't handle them right.

Be careful with blocks (and bindings); they keep a reference to all
local variables that are (potentially) visible in the block, even if
those variables aren't actually used in the block. Any values attached
to those local vars not be garbage collected until the whole block is.
Here's an example:

  def foo
     a1=%w[foo bar baz]
     a2=%w[shish boom bah]
     a3=%w[this one's actually used]
     return bar { p a3 }
  end

  def bar(&block)
    return block
  end

a1 and a2 are leaked (temporarily). Even tho they're unused, they
don't actually get GC'd until block is also GC'd.

You can also use ObjectSpace.each_object to iterate over currently
live objects; this might help you determine which objects are being
leaked.