in reply to Re^3: While loop and LAST
in thread While loop and LAST
I don't quite understand while there is a big difference in memory and performance.
The for loop creates a list of the keys which is allocated on the (perl) stack.
Effectively, it has to perform the equivalent of your while loop (discarding the values) to generate that list and needs to allocate memory to construct the list
It then iterates that list and has to do a second lookup of each key to obtain the value.
And each time you short-circuit the loop with next, large chunks of the work done to build the list will be discarded and it all needs to be re-done for the next iteration of the outer loop.
Conversely, the while loop retrieves both key and value together with no secondary lookup and no need to allocate memory. Resetting the iterator with keys %hash; in a void context is a simple, single assignment. And when you short-circuit the loop; you not only don't discard substantial effort already expended; you avoid expending the effort that would be discarded. That's a double saving.
Even if your hash is of relatively modest size; those savings will be multiplied by the iteration count of the outer loop and will make a considerable difference.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^5: While loop and LAST
by mcoblentz (Scribe) on Nov 02, 2013 at 18:39 UTC |