As mentioned recently in the Acky Memory thread Perl's Garbage Collector is based on reference count. Any variable (actually any piece of memory ever allocated so I guess this also includes lists for example) as an associated reference count. This count is incremented when the variable is created (to 1!) and every time another variable references it. It is decremented when the variable goes out of scope or when a reference does not reference it anymore. Once the count gets to 0 the memory is freed (and available to the rest of the process but not to the OS as merlyn noted).

The problem with this (usually quick and efficient) scheme is with circular references: if 2 variables reference each other then even when they get out of scope their reference count stays at 1 and the memory never get released. This is quite frequent with complex structures, such as trees for example, where a parent might reference a child which in turn references the parent.

Fixing this problem involves either "breaking the loop" in the DESTROY method (while not destroying too much though), or using the Devel::WeakRef module which allows you to create references that do not increase the reference count (warningI have never used that module and I don't know it's state, especially I have no idea if the patch to the Perl core that comes with it is still valid, if it has been integrated in the core or if the module cannot be used with 5.6, I'd be glad to learn more about it though!).

Item 34 of Effective Perl Programming has a nicely illustrated example of circular data structure and how to deal with it.


In reply to Re: garbage collection guts by mirod
in thread garbage collection guts by Anonymous Monk

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.