http://www.perlmonks.org?node_id=814396


in reply to Optimizing Iterating over a giant hash

This might be a little better.

my $temp; while (($entry,$temp) = each %my_hash) { foreach $timeStamp ( sort keys %$temp) { my @tskeys = sort keys %{$temp->{$timeStamp}}; print $Hentry "$entry\t$timeStamp\t", scalar @tskeys; print $Hentry "\t$_\t", $my_hash{$entry}{$timeStamp}{$_} for @tske +ys; print $Hentry "\n"; } }

What I've done here is factor out the repeated call to keys on %{$temp->{$timeStamp}} and turned the foreach my $id loop into the statement modifier form. The lack of a block might be faster.

Replies are listed 'Best First'.
Re^2: Optimizing Iterating over a giant hash
by ruzam (Curate) on Dec 26, 2009 at 20:00 UTC

    Fully agree with eliminating the multiple call to keys.

    I'm also a big believer in reducing nested hash references. For the small price of assigning another variable, you can eliminate the cost of several steps of hash key lookups, and improve readability as a bonus.

    my $temp; while (($entry,$temp) = each %my_hash) { foreach $timeStamp ( sort keys %$temp) { my $hash_ref = $temp->{$timeStamp}; my @tskeys = sort keys %$hash_ref; print $Hentry "$entry\t$timeStamp\t", scalar @tskeys; print $Hentry "\t$_\t", $hash_ref->{$_} for @tskeys; print $Hentry "\n"; } }