P
Peter J. Holzer
Some time ago we had a discussion about the FAQ "How can I free an array
or hash so my program shrinks?". I claimed that on Linux and other OSs
with modern malloc implementations (probably BSDs including MacOS and
Windows) perl can and does return memory to the OS, but couldn't come up
with an example. Now I found one:
#!/usr/bin/perl
use warnings;
use strict;
sub a {
print "a\tcall\t", vm(), "\n";
my $h;
for ('a' .. 'z') {
$h->{$_} = $_ x 1_000_000;
}
print "a\treturn\t", vm(), "\n";
return $h;
}
sub c {
print "c\tcall\t", vm(), "\n";
a();
print "c\treturn\t", vm(), "\n";
}
c();
sub vm {
open(my $fh, '<', "/proc/$$/status");
while (<$fh>) {
chomp;
return $_ if (/^VmSize:/);
}
}
__END__
On my Linux box, this prints:
c call VmSize: 5056 kB
a call VmSize: 5056 kB
a return VmSize: 31516 kB
c return VmSize: 6036 kB
demonstrating that the process grows by roughly 26 MB as the anonymous
hash is created and then shrinks again when the reference to it goes out
of scope. This also works with a simple hash or array. For simple
(large) scalars it is more complicated: Memory does get freed sometimes,
but it isn't easy to determine when.
hp
or hash so my program shrinks?". I claimed that on Linux and other OSs
with modern malloc implementations (probably BSDs including MacOS and
Windows) perl can and does return memory to the OS, but couldn't come up
with an example. Now I found one:
#!/usr/bin/perl
use warnings;
use strict;
sub a {
print "a\tcall\t", vm(), "\n";
my $h;
for ('a' .. 'z') {
$h->{$_} = $_ x 1_000_000;
}
print "a\treturn\t", vm(), "\n";
return $h;
}
sub c {
print "c\tcall\t", vm(), "\n";
a();
print "c\treturn\t", vm(), "\n";
}
c();
sub vm {
open(my $fh, '<', "/proc/$$/status");
while (<$fh>) {
chomp;
return $_ if (/^VmSize:/);
}
}
__END__
On my Linux box, this prints:
c call VmSize: 5056 kB
a call VmSize: 5056 kB
a return VmSize: 31516 kB
c return VmSize: 6036 kB
demonstrating that the process grows by roughly 26 MB as the anonymous
hash is created and then shrinks again when the reference to it goes out
of scope. This also works with a simple hash or array. For simple
(large) scalars it is more complicated: Memory does get freed sometimes,
but it isn't easy to determine when.
hp