but it does allocate new memory before running bar, even though it could reuse $var's memory for $var2.

No, that would defy the optimization of not deallocating it in the first place.

For Perl to know when $var is not currently being used, it would have to 1) place $var on a free list when it stops being used and 2) remove it from the free list when $var is in use again. Those two operations are known as deallocation and allocation, exactly what the optimization is trying to avoid!

Keep in mind that each variable consists of two memory blocks, three if they have a string buffer associated with them. And that's just for non-magical scalars. A lot of CPU time is being saved.

One question remains: When does perl free memory?

Anon SVs are freed. SVs that become anon (such as return values) are freed. SVs passed to undef have their attached buffer freed.

Keep in mind that all of this is the result of an (undocumented?) optimization. It shouldn't be relied upon. It's just that you can't rely on it not happening.


In reply to Re^4: out of memory problem by ikegami
in thread out of memory problem by lightoverhead

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.