Kozz has asked for the wisdom of the Perl Monks concerning the following question:

As I was writing up some subroutines in some scripts I was doing, I got to remembering reading someone's comments, "why thrash memory?". And indeed, we can all agree that if you can lessen the total memory used by your script that it's a good thing, no? So here's my question: When is it important to undef($variable) simply for the sake of being "nice" to memory? If the variable is going out of scope in another 0.25 seconds, should I forget about undefining that value? Or more importantly, when is it imperative that you undefine something?

Replies are listed 'Best First'.
Re: Why Thrash Memory?
by chromatic (Archbishop) on Apr 01, 2000 at 01:03 UTC
    For the most part, Perl's garbage collection will handle discarding variables and cleaning up for you automatically. As you suggest, if you're mindful of the imminenet death of a variable scope, don't worry about calling undef.

    With that in mind, there are a couple of places where you might want to massage things by hand.

    • When you have a circular data structure, like a doubly linked list or some other monstrosity. As the gc works by reference counting, if you have two objects that only point to each other, they'll still stick around. Break the links or undefine one or both objects.
    • When you won't be leaving the scope for a while, but you have an item using lots of memory. One example would be performing some sort of transformation on a large data file. If you must do it all in memory (for speed reasons) but you copy it from one scalar to another, undef the first scalar as soon as possible.
    The first is the only one I'd really worry about -- with some thoughtful programming, the second may never come up. I really don't worry about it much, as wise coding tends to minimize memory usage anyway.
      Re: #1--if you're interested, Perl 5.6 has (experimental) support for weak references, meaning that you can use circular references (as one example) and have the standard garbage collection work for you. A weak reference doesn't increment the reference count of the thing to which it refers.

      You'll need the WeakRef module.

Re: Why Thrash Memory?
by stephen (Priest) on Apr 01, 2000 at 04:01 UTC
    Generally, I think that it's better to let garbage collection handle it, since undef()s clutter the code. That being said, it might be worth it if the variable is something simply huge... in which case it might be worth it to deal with the data in smaller chunks.

    I think I've just succeeded in echoing chromatic again.


A reply falls below the community's threshold of quality. You may see it by logging in.