http://www.perlmonks.org?node_id=1060962


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.


With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^5: While loop and LAST
by mcoblentz (Scribe) on Nov 02, 2013 at 18:39 UTC
    Oh! That's a great explanation, thank you. With a possible 100 or so keys to iterate, over possibly 100 job listings, over 10 companies, that's quite a pile of work. Not quite a million, but quite significant nonetheless.