in reply to Can we determine when the garbage collector works?

Perl has no Garbage Collection, because Perl does Reference Counting.

Most likely, you don't code with pointers but with references, and the only thing you have to fear with Reference Counting are circular references, as the reference count for these can never reach zero and thus the memory never be reclaimed.

There are two ways around this - one way is to have an explicit destroy() method that the user is supposed to call - a stupid idea in my opinion, but sometimes less hassle than the second option. Scalar::Util has weaken(), which allows you to create weak references, that is, references which do not increase the reference count for the referenced object. With that, structures containing circular references can also be reclaimed as soon as the last strong reference falls out of scope.

Note that a closure never goes out of scope as the subroutine never gets released, and thus the memory held by the closure cannot be reclaimed automatically (if at all before process exit).

Steve_p points to Devel::Cycle and Test::Memory::Cycle to hunt down the circular references in your programs.

  • Comment on Re: Can we determine when the garbage collector works?

Replies are listed 'Best First'.
Re: Re: Can we determine when the garbage collector works?
by Doraemon (Beadle) on May 12, 2004 at 15:24 UTC
    Since we can't reclaim automatically the memory in closure, is that mean i still need to traverse down (i wonder why not up? :)) the tree?

      First, a very simple example of a closure:

      { my $tree; sub get_tree { return $tree; }; };

      In the above example, $tree and all memory referenced by it will never go out of scope, and since $tree is invisible outside of its containing block, there is no way to free up the referenced memory.

      { my $tree; sub get_tree { return $tree; }; sub release_tree { undef $tree; }; };

      In this example, it is possible to release the memory structure referenced by $tree by calling release_tree, because it also sees the $tree variable. But this release is not automatic and thus must be done by the programmer when the time has come.