Getting rid of variables after you have finished with them
Archive - Originally posted on "The Horse's Mouth" - 2006-06-06 09:27:22 - Graham Ellis
If you've finished with a variable in your program, you can usually just leave it "in situe" and it will be destroyed and the memory it occupied will be released when you exit from your program. In many languages, variables within named blocks of code have an even shorter "shelf life" - by default, a PHP or Python variable used within a function will be lost once you leave the function, and in Perl any variable described as a "my" variable will be lost at the end of the block in which it is declared. There *are* exceptions - if a variable reference is copied (Perl or Python) and / or if a PHP variable is declared as being static to name just a couple of examples.
But what if I've got a long-running program and I want to release the memory that a variable occupies once I've finished with it? Most languages support TWO ways of getting rid of variables:
a) You can set the variable to being empty. In this case, the variable name still exists but it contains no data, so what might previously have been a memory hog is shrunk to virtually nothing
b) You can actually remove the variable name itself from the symbol table, so that the very name ceases to exist.
If you would a metaphor - if you consider that a variable is like a cage that contains animals, then setting the variable to empty is like getting rid of the animals, and removing the variable is like destroying the whole structure of the cage.
Python
To set a variable to empty, assign None to it: queue = None
To destroy a variable, use the del keyword: del queue
Perl
To set a variable to empty, undef it: undef @queue;
To destroy a variable, you may be able to use delete (but this applies only to hash members and as from Perl 5.6 to list members too: delete $queue{"X72"};
PHP
To set a variable to empty, assign 'nothing' to it, for example: $?queue = NULL;
or $queue = "";
To destroy a variable, use unset: unset($queue);
Tcl, Tcl/Tk, Expect
To set a variable to empty, assign an empty string to it: set queue ""
To destroy a variable, use unset: unset queue
Please note that under most operating systems, memory released by emptying or destroying variables will be available for re-use by the current process, but will NOT be released back to the operating system until the process terminates. This applies to all languages, not just the ones I've highlighted in this article, as most operating systems aren't built to handle memory returned to them by shrinking processes.