perlquestion
bloonix
<p>Hi Monks, I'm trying to understand the garbage collector. Please have a look at my code example:</p>
<code>
#!/usr/bin/perl
use strict;
use warnings;
package Foo;
sub new {
my $self = bless { }, shift;
for (1..2_000_000) {
$self->{x} .= "x" x 1000;
}
return $self;
}
package Bar;
sub new {
my $self = bless { }, shift;
for (1..2_000_000) {
$self->{$_} = "x" x 1000;
}
return $self;
}
package main;
print "### Test Foo\n";
my $foo = Foo->new;
print "Object created\n";
print "Size: ", qx{ps -p $$ -o rss=};
$foo = undef;
sleep 3;
print "Object destroyed\n";
print "Size: ", qx{ps -p $$ -o rss=};
print "### Test Bar\n";
my $bar = Bar->new;
print "Object created\n";
print "Size: ", qx{ps -p $$ -o rss=};
$bar = undef;
sleep 3;
print "Object destroyed\n";
print "Size: ", qx{ps -p $$ -o rss=};
</code>
Output:
<pre>
### Test Foo
Object created
Size: 1955472
Object destroyed
Size: 2348
### Test Bar
Object created
Size: 2647552
Object destroyed
Size: 2631164
</pre>
<p>The Foo example is that what I expect. But I don't understand why the memory is not releases back to the operating system in the Bar example.</p>
<p>Could someone bring some light into my darkness?</p>
Cheers,
Jonny