Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: each or keys?

by btrott (Parson)
on Oct 11, 2000 at 02:34 UTC ( [id://36144]=note: print w/replies, xml ) Need Help??


in reply to each or keys?

You wrote:
> Now I understand that 'keys' would have to > generate a list which might be expensive I > guess, but I'm still a bit puzzled by the results.
Well, you hit the proverbial nail on the head there, though. So I'm not sure there's much to be puzzled about, unless you're just wondering why keys is so slow at generating the list.

But it is that very fact--that keys has to generate a list of the keys each time--that makes it so much slower when breaking early out of the loop. Simply put, you need to do *much* less work when you break early out of the loop when using each, because you haven't had to iterate over the entire hash and build a list.

If, for example, you build the list of keys before you run the benchmark, then in k iterate over that list instead of calling keys anew, you'll find that indeed it is that call that's slowing it down.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://36144]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others having a coffee break in the Monastery: (3)
As of 2024-04-24 19:22 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found