Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

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

by Laurent_R (Canon)
on Nov 01, 2013 at 11:20 UTC ( [id://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.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others chanting in the Monastery: (3)
As of 2024-04-25 07:28 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found