Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

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

by Laurent_R (Canon)
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.

Log In?

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

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

    Results (288 votes). Check out past polls.