[Israel.pm] GC for iterator

Mikhael Goikhman migo at homemail.com
Tue Aug 23 01:56:39 PDT 2005


On 23 Aug 2005 11:07:31 +0300, Pinkhas Nisanov wrote:
> 
> I try to work with iterators in perl and
> do not really know how garbage collector
> will work in this case, example:
> 
> {
>     my $itr1 = createIterator( 1, 100000);
>     $itr1->() foreach ( 1..20 );
> }
> 
> sub createIterator
>   {
>     my ( $p1, $p2 ) = @_;
>     return sub { print "next value: ". ++$p1. "\n" if $p1 < $p2 }
>   }
> 
> Variables "$p1" and "$p2" stay in memory, so iterator "$itr1"
> ( reference to function ) remember their values on every
> iterator call. My question is, will garbage collector release
> variables "$p1" and "$p2" when iterator "$itr1" go out of scope?

Yes. The only references to $p1 and $p2 are in the anonymous sub.
Therefore these variables will be freed after the sub is freed.
This is not guaranteed to be instant AFAIK, but it is usually instant.

Just bless your vars and add DESTROY to see when exactly they are freed.
The following perl program demostrates this:

	package DebugDestroy;
	sub new { bless \($_[1]), $_[0] }
	sub DESTROY { print "Value '${$_[0]}' is freed\n" }

	package main;
	{ my $itr = createIterator(1, 100000); $itr->() foreach 1..10 }
	{ my $itr = createIterator(2, 200000); $itr->() foreach 1..20 }

	sub createIterator {
		my ($p1, $p2) = @_;
		DebugDestroy->new($p1);
		return sub { print "next value: ", ++$p1, "\n" if $p1 < $p2 }
	}

Regards,
Mikhael.

-- 
perl -e 'print+chr(64+hex)for+split//,d9b815c07f9b8d1e'



More information about the Perl mailing list