Garbage Collection, Circular References, and Weak References
High-level languages typically allow programmers not to worry about deallocating memory when they’re done using it. This automatic reclamation process is known as garbage collection. For most purposes, Perl uses a fast and simple reference-based garbage collector.
When a block is exited, its locally scoped variables are normally freed up, but it is possible to hide your garbage so that Perl’s garbage collector can’t find it. One serious concern is that unreachable memory with a nonzero reference count will normally not get freed. Therefore, circular references are a bad idea:
{ # make $a and $b point to each other
my ($a, $b);
$a = \$b;
$b = \$a;
}or more simply:
{ # make $a point to itself
my $a;
$a = \$a;
}Even though $a should be
deallocated at the end of the block, it isn’t. When building
recursive data structures, you’ll have to break (or weaken; see
below) the self-reference yourself if you want to reclaim the memory
before your program (or thread) exits. (Upon exit, the memory will
be reclaimed for you automatically via a costly but complete
mark-and-sweep garbage collection.) If the data structure is an
object, you can use a DESTROY
method to break the reference automatically; see Garbage Collection with destroy
Methods in Chapter 12.
A similar situation can occur with caches—repositories of data designed for faster-than-normal retrieval. Outside the cache there are references to data inside the cache. The problem ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access