Beefy Boxes and Bandwidth Generously Provided by pair Networks
P is for Practical
 
PerlMonks  

Re: Creating hash of arrays (in a faster way)

by Laurent_R (Vicar)
on Nov 01, 2013 at 11:20 UTC ( #1060742=note: print w/ replies, xml ) Need Help??


in reply to Creating hash of arrays (in a faster way)

To start with, just one (possibly silly) question: are you sure that the data structure you obtain with the "correct but slow" code is really what you want? I am asking that because the data structure you get with that does not seem terribly useful (at least in the limited context). A simple hash would appear to be more useful, and, in that case, the first attempt (which you qualify as wrong) seems OK.

Now, assuming that you really want a hash of arrays such as the one you build in your second code snippet, if anything is slow, it is probably not so much the foreach construct, which is pretty fast, but the fact that you are shifting the @values each time, meaning that Perl has to recalculate the @values array at each iteration.

The map version proposed by choroba is likely to be faster not so much because map is faster than foreach (most benchmarks that I have done show that the difference between the two constructs is usually quite small and foreach is quite often slightly faster, at least when they allow similar syntax constructs), but because it does not shift the @values array each time.

I did not do benchmarks and I may turn out to be wrong in that specific case, but I just wanted to call your attention on that for your consideration if you are going to benchmark various solutions.

Update: I was interrupted while writing the above and had to do something else. When I started to write this, there was only one answer (choroba's), I would probably not have written the above if I had seen all the other useful answers that came in between, since it turns out I am probably not saying very much new.


Comment on Re: Creating hash of arrays (in a faster way)
Select or Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others having an uproarious good time at the Monastery: (5)
As of 2014-07-28 05:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    My favorite superfluous repetitious redundant duplicative phrase is:









    Results (186 votes), past polls