in reply to Re: Garbage collection of 'my' variables
in thread Garbage collection of 'my' variables
I've been afraid that this would become a bad meme and it appears to be happening (unless you are just replying to the subject line and not to the question actually posed in the article -- though the wording could be clearer, I admit).
The fact that memory used directly by a lexical is not freed when the lexical goes out of scope is not much of an issue here for at least a couple of reasons.
The primary reason is that the memory will get reused when you come back into the subroutine (and this is the reason that the memory wasn't freed -- Perl selecting "use more memory" at every design trade-off, this time over the alternative of "spend CPU time to free memory that you may later just need to reallocate"). So this would not explain the constantly increasing consumption of virtual memory (which is what the original question is about -- though you'd have to read it very carefully to figure that out, I think).
The other item to note is that most of the memory consumed by @pixels is freed! When the @pixels array goes out of scope, each of the elements in @pixels is freed (since there are no other references to them), but the memory used by @pixels itself is not freed. This memory is roughly propotional to the maximum number of elements ever stored in @pixels.
Anyway, I say that this is becoming a "bad meme" because I am increasingly hearing people spouting off "lexicals aren't freed" w/o including all of the "however"s that should go along with such a statement. I think that most of the time, the "however"s are more important. That is, most of the time, the fact that the memory used directly by the lexical is not freed doesn't matter much.
It is only when you store a really large string directly into a lexical that this matters much at all. And even then, it is a one-time hit (per lexical) and so won't cause memory to grow and grow w/o bound (like several other things will).
Back to the original problem, I'd probably use something more like:
in this case.while( $data =~ /(\S+)/g ) { $average[0] += hex substr( $1, 1, 2 ); $average[1] += hex substr( $1, 3, 2 ); $average[2] += hex substr( $1, 5, 2 ); }
Update: BTW, your suggestion to set the array to an empty list would do nothing. Setting an array to an empty list frees the elements (which will already happen) and doesn't free the memory for the array itself (which is also what will already happen). You can undef the array (undef @pixels;) to free the memory that it uses directly, but this is rarely a good idea (or else Perl would be doing that by default).
- tye (but my friends call me "Tye")
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: (tye)Re: Garbage collection of 'my' variables
by perrin (Chancellor) on Aug 29, 2001 at 01:37 UTC |