On Mon, 17 Apr 2000, Perrin Harkins wrote:
> What I know about Perl internals could fit on the head of a pin, but
> this strikes me as a very odd statement. If the garbage collector is
> never used, why do my lexical variables go out of scope and get
> destroyed? There are mod_perl packages like Apache::Session that
> absolutely depend on garbage collection of lexical variables to work.
> Are you saying that destroying the variables and actually reclaiming the
> memory are separate, and only the first is happening?
excactly, lexicals "go out-of-scope", but most of the memory allocations
are not freed unless you explicitly undef. e.g.:
sub foo {
my $string = shift;
print $string;
}
foo("hello world");
after the subroutine is called, the SvPVX field of $string hangs onto the
allocated length("hello world") + 1, unless you undef $string;
this is an optimization, Perl assumes if you've allocated for a variable
once, you'll need to do it again, making the second assignment+ much
cheaper. the elements of lexical arrays and hashes are released (well,
the refcnt is decremented, which triggers free if the refcnt was 1) when
one goes of-of-scope, but the size of the array/hash remains for the same
reasons. this is another reason it's always best to pass a reference when
possible, for $strings, @arrays and %hashes, to avoid these copies.
a the B::Size B::LexInfo packages on cpan were written to illustrate this,
though one or both needs fixing for 5.6.0, which i'll get to soon.