Ah. ok. I was under the impression that variables declared within a function are 'created', and the memory for them is not un-allocated after it is complete. |
AFAIK, your understanding is correct.
All
memory for local variables is "allocated" upon function entry. However objects are not
constructed until the actual declaration line. Therefore it is typically more efficient to declare variables/object in the smallest scope possible, that way their construction/destruction can be skipped if the object is never used.
There are exceptions, of course. Constructing an object inside of a loop body would result in repeated construction/destruction which is usually very wasteful.
That said....
I put the term "allocated" in quotes above because it's not what you think. Local variables are put on the stack. They're not allocated on the heap.
The stack operates differently from the heap. Heap memory is requested as needed, so the more you consume, the more memory your program uses.
Stack memory is taken from a pre-allocated block of memory that has been designated for stack space. Consuming more stack space does not cause your program to use more memory in the eyes of the OS. It's more like you're making use of memory your program has already allocated. Therefore it is not at all inefficient for the program to "allocate" space for all local vars up front.
Reducing the amount of stack space used by your program is not really an optimization. It will not increase speed or reduce memory consumption. Stack space is practically free and there is no downside to using more of it.
Until, of course, you run out. But that typically doesn't happen unless you are doing very deep recursion and/or putting ridiculously large arrays/objects on the stack.