Yes there is a faster way. Use the "reverse" function:

     my %hash = (dog => 'house', pig => 'barn', bird=> 'cage');
     my %rhash = reverse %hash;
     if ($rhash{house}) {
         print "Found house.\n";
     }

That's a really good looking idiom, but I see it is less efficient
than the foreach method. According to Benchmark:

~/Perl $ perl reverse-hash-benchmark.pl
Benchmark: timing 1000000 iterations of foreach_hash, reverse_hash...
foreach_hash:  3 wallclock secs ( 4.35 usr +  0.00 sys =  4.35 CPU) @
229885.06/s (n=1000000)
reverse_hash:  6 wallclock secs ( 6.81 usr +  0.01 sys =  6.82 CPU) @
146627.57/s (n=1000000)
                Rate reverse_hash foreach_hash
reverse_hash 146628/s           --         -36%
foreach_hash 229885/s          57%           --
~/Perl $

Below is the code I used:

<code>
#!env perl

use strict;
use warnings;

use Benchmark qw(:all);

sub reverse_hash {
   my %hash = ( dog => 'house', pig => 'barn', bird => 'cage' );
   my %rhash = reverse %hash;
   if ( exists $rhash{house} ) {
       return 1;
   }
}

sub foreach_hash {
   my %hash = ( dog => 'house', pig => 'barn', bird => 'cage' );
   foreach ( keys %hash ) {
       if ( $hash{$_} eq 'house' ) {
           return 1;
       }
   }
}

my $results = timethese(
   1000000,
   {
       reverse_hash => \&reverse_hash,
       foreach_hash => \&foreach_hash,
   }
);

cmpthese($results)

</code>

Maybe I'm doing the Benchmark in a wrong way, or is really more
expensive reversing a hash than iterating its keys using foreach?
--
Igor Sutton Lopes <[EMAIL PROTECTED]>

--
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
http://learn.perl.org/


Reply via email to