Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change

Re^4: While loop and LAST

by BrowserUk (Pope)
on Nov 02, 2013 at 17:08 UTC ( #1060962=note: print w/replies, xml ) Need Help??

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.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1060962]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others chilling in the Monastery: (5)
As of 2018-02-22 09:25 GMT
Find Nodes?
    Voting Booth?
    When it is dark outside I am happiest to see ...

    Results (289 votes). Check out past polls.