Consider the code in Example 14-1.
use GTop ( ); my $gtop = GTop->new; my $proc = $gtop->proc_mem($$); print "size before: ", $gtop->proc_mem($$)->size( ), " B\n"; { my $x = 'a' x 10**7; print "size inside: ", $gtop->proc_mem($$)->size( ), " B\n"; } print "size after: ", $gtop->proc_mem($$)->size( ), " B\n";
When executed, it prints:
size before: 1830912 B size inside: 21852160 B size after: 21852160 B
This script starts by printing the size of the memory it occupied when it was first loaded. The opening curly brace starts a new block, in which a lexical variable $x is populated with a string 10,000,000 bytes in length. The script then prints the new size of the process and exits from the block. Finally, the script again prints the size of the process.
Since the variable $x is lexical, it is destroyed at the end of the block, before the final print statement, thus releasing all the memory that it was occupying. But from the output we can clearly see that a huge chunk of memory wasn't released to the OS—the process's memory usage didn't change. Perl reuses this released memory internally. For example, let's modify the script as shown in Example 14-2.
use GTop ( ); my $gtop = GTop->new; my $proc = $gtop->proc_mem($$); print "size before : ", $gtop->proc_mem($$)->size( ), " B\n"; { my $x = 'a' x 10**7; print "size inside : ", $gtop->proc_mem($$)->size( ), " B\n"; } print "size after : ", $gtop->proc_mem($$)->size( ), " B\n"; { my $x = 'a' x 10; print "size inside2: ", $gtop->proc_mem($$)->size( ), " B\n"; } print "size after2: ", $gtop->proc_mem($$)->size( ), " B\n";
When we execute this script, we will see the following output:
size before : 1835008 B size inside : 21852160 B size after : 21852160 B size inside2: 21852160 B size after2: 21852160 B
As you can see, the memory usage of this script was no more than that of the previous one.
So we have just learned that Perl programs don't return memory to the OS until they quit. If variables go out of scope, the memory they occupied is reused by Perl for newly created or growing variables.
Suppose your code does memory-intensive operations and the processes grow fast at first, but after a few requests the sizes of the processes stabilize as Perl starts to reuse the acquired memory. In this case, the wisest approach is to find this limiting size and set the upper memory limit to a slightly higher value. If you set the limit lower, processes will be killed unnecessarily and lots of redundant operations will be performed by the OS.
 
Continue to: