質問

I have a hash of arrays. Which is the most efficient and fastest way to loop through it.

my %h1 = (
  C1 => ['3','1','2'],
  C2 => ['6','2','4'],
  C3 => ['8', '1'],
 );

OPTION 1

foreach my $key ( keys %HoA )  {
    print "Articles in group $key are: ";
    foreach ( @{$HoA{$key}} )  {
    print "$_\n";
    }
}

OPTION 2

while( my ($k, $v) = each %HoA ) {
    print "Articles in group $k are: @$v\n";   
}

Which one would save me time if I would looping through a huge HoA.

役に立ちましたか?

解決

It is my understanding that keys will pre-construct a complete list of all the hash keys, and this can result in a substantial amount of memory being used for a large hash. I think this is one point of consideration, since you say you have a huge HoA.

Some of the main differences for me are that sometimes you want a list sorted by value or the number of array elements, and I don't think you can control the order of the key-value pair that each returns. So, in the situation where you need a sorted list, I would use keys. If your hash is very, very large and you need both the key and value but the order is not important, I would use each because it only returns a list of two elements (your key-value pair). The other thing to consider is the use of a database, as others suggested, but that may come at a cost depending on the size of your data.

I think it is hard to answer the question "is keys faster than each?" without knowing more about the data (and testing it directly), but I think it may be easier to answer the question "should I be using keys or each in this situation?" Depending on your goal and what "huge HoA" means, I think it's possible that one method may be more efficient and result in better performance, at least in terms of memory. Others may have different opinions and experience on this subject, so I'd appreciate any feedback.

他のヒント

Using each is likely to be clearer and perhaps fractionally faster, but you won't gain anything significant however you do it.

while (my ($key, $val) = each %HoA) {
    print "Articles in group $key are: ";
    foreach ( @$val )  {
        print "$_\n";
    }
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top