|Perl Monk, Perl Meditation|
This post answers a few common questions and misconceptions about Perl's memory management.
Lexical variables don't get freed at end of scope
Lexical variables don't get freed at end of scope. They are cleared on scope exit to give you the apperance of a fresh variable. This is an optimisation that should be transparent to you.
On scope exit, if anything prevents the variable from being resused (e.g. if there are remaining references to the variable), the existing variable becomes anonymous and a new variable is allocated.
Clearing a variable does not free the memory it uses
It was previously mentioned that variables on cleared on scope exit. Variables can also be cleared as follows:
Clearing a variable frees no memory directly. The buffer of a string is marked as being unused, but it remains allocated for later use. The underlying array of pointers in arrays and hashes is cleared, but it remains allocated for later use. This is an optimisation that should be transparent to you.
As a result of a variable being cleared, referenced variables (incl array elements) have their refcount lowered, and that may free those variables. But not the variable being cleared.
undef does not free a variable
undef can be used to clear a variable.
undef does do more than clear the variable. It also frees any buffers the variable has.
This function is rarely useful.
However, undef will never free a variable. Clearing the variable may result in the reduction of the ref counts of other variables, which may free those variables. But not the variable that was passed to undef.
Freeing variables may result in no change in available system memory
You can't rely on memory being returned to the system, but it can happen.
If and when memory is returned to the OS is dependant on the memory allocation mechanism perl was compiled to use. You may also see differences between system using the same memory allocation mechanism. It's also possible that a mechanism will only ever release the large blocks it allocated.
The default memory allocation mechanism varies by OS. You are more likely to see memory being released to the OS on Windows.