Strictly speaking, you really do not know. The official documentation is somewhat cautious when discussing memory usage. If and when memory is freed, it depends on the internal elements of perl. Any answers to your question are based on knowledge (or assumptions) about the internal components that are subject to change. However, there are a couple of things we can know:
- The memory used by perl will be fixed by the operating system when the execution is completed.
- The memory allocated for a variable cannot be freed if there is any reference to it.
There are no guarantees beyond this, although perlguts provides some insight into the behavior of internal elements:
Perl uses a link-based garbage collection mechanism. SVs, AVs or HV (xV for brevity in the following) begin their life with reference counter 1. If the countdown of the xV reference ever drops to 0, then it will be destroyed and its memory will become available for reuse.
This usually does not happen at the Perl level, unless the undef'ed variable or the last variable containing a reference to it is changed or overwritten.
The memory “reusable” is not quite the same as the release. This allows perl to use memory for something else, but does not return it to the operating system. You should not expect perl to return memory to the OS before exiting.
From a developer's point of view, my memory management tip is:
- Do not load more data into memory immediately than necessary. (e.g. read files one at a time, rather than tearing apart if possible)
- Declare limit variables in the smallest reasonable area.
- Do not keep links to data when it is no longer needed. (Or let it go out of scope or explicitly clear the link.)
- Define large variables when they are no longer needed. (e.g. via
undef %hash
)
Performing these steps will not necessarily free / reuse the memory, but it maximizes the chances that it will be.
source share