Perl doesn't use garbage collection per se, but rather reference counting.
Which basically means that memory is handed back to the memory pool, once it is no longer referenced. Automatically.
In this snippet:
sub fred {
my( $x, $y ) = @_;
my $result = $x * $y;
return $result;
}
When the sub returns, none of the variables inside it can be referenced from anywhere else, so their reference counts are zero, and their memory will be returned to the pool, as the subroutine ends.
In this snippet: sub genList {
my( $start, $end, $step ) = @_;
my @list;
for( my $i=$start; $i < $end; $i += $step } push @list, $i;
return \@list;
}
...
if( ??? ) {
my $arrayRef = getList( 10, 99, 3 );
## use list
}
The contents of array @list persists beyond the life of genList(), because the array is returned by reference; thus its reference count has been incremented, and is non-zero when genList() ends.
However, when the calling if block ends, that reference count will be decremented, and as it will drop to zero, the memory will be freed back to pool.
Bottom line: for the most part, Perl programmer's do not worry about, or suffer from, memory leaks. Nor does their code suffer those awful pregnant pauses whilst the garbage collector goes off searching through memory trying to find and clean up no longer used space. Memory is reclaimed automatically, on the fly, as soon as it is no longer needed.
It is possible to create memory leaks, by creating self-referencing structures, but you have to work hard to do it, and there are techniques -- weakening -- to deal with it if, the self-referential data is a deliberate need, rather than accidental. In 15 years of daily Perl, including a lot of very heavy data processing, I've never needed to use weakening.
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
In the absence of evidence, opinion is indistinguishable from prejudice.
|