in reply to Re^3: Tracking down memory leaks
in thread Tracking down memory leaks

Note that in your example, Perl will keep the memory for $big_string twice:
#!/usr/bin/perl use strict; use warnings; use Readonly; Readonly my $size => 10 * 1024 ** 2; # 10 Mb. sub show_mem { system "grep ^VmSize /proc/$$/status"; } sub gimme_big { my $size = shift; my $var = 'x' x $size; } show_mem; gimme_big $size; show_mem; __END__ VmSize: 3464 kB VmSize: 23952 kB
For a 10Mb string, Perl allocates about 20Mb memory.

undefing the variable makes Perl allocate about 10Mb less:

#!/usr/bin/perl use strict; use warnings; use Readonly; Readonly my $size => 10 * 1024 ** 2; # 10 Mb. sub show_mem { system "grep ^VmSize /proc/$$/status"; } sub gimme_big { my $size = shift; my $var = 'x' x $size; undef $var; } show_mem; gimme_big $size; show_mem; __END__ VmSize: 3472 kB VmSize: 13716 kB
So, how do we get rid of the extra 10Mb? By a careful use of string eval:
#!/usr/bin/perl use strict; use warnings; use Readonly; Readonly my $size => 10 * 1024 ** 2; # 10 Mb. sub show_mem { system "grep ^VmSize /proc/$$/status"; } sub gimme_big { my $size = shift; my $var = eval "'x' x $size"; undef $var; } show_mem; gimme_big $size; show_mem; __END__ VmSize: 3468 kB VmSize: 3468 kB