perl - Is hashref in array?

Paul Seamons paul at seamons.com
Wed Jan 10 13:36:37 MST 2007


> Hmmm ... I feel a benchmark coming on ...

> Mine is about 10% faster.  Not much of a difference really.

Beware the benchmark.  Different datasets and CPU loads will yield different 
results.

use Benchmark qw(cmpthese timethese);

my @tree;
my $zero = { a => "0", b => "0" };
my $one = { a => "1", b => "1" };
push @tree, $zero, $one, $zero, $one;

# alan random orders the stringification of the hashrefs
# greg sorts the uniques
# paul random orders the uniques
sub alan { my @unique = do { my %s; @s{ @tree } = ''; keys %s } }
sub greg { my @unique = do { my %s; grep { ! $s{ $_ }++ } @tree } }
sub paul { my @unique = do { my %s; @s{ @tree } = @tree; values %s } }

cmpthese timethese(-10, {
  greg => \&greg,
  alan => \&alan,
  paul => \&paul,
});


paul at paul-laptop:~$ perl /home/paul/foo
Benchmark: running alan, greg, paul for at least 10 CPU seconds...
      alan: 18 wallclock secs (10.29 usr +  0.00 sys = 10.29 CPU) @ 93772.50/s 
(n=964919)
      greg: 18 wallclock secs (10.38 usr +  0.00 sys = 10.38 CPU) @ 96677.84/s 
(n=1003516)
      paul: 18 wallclock secs (10.33 usr +  0.02 sys = 10.35 CPU) @ 95057.00/s 
(n=983840)
        Rate alan paul greg
alan 93772/s   --  -1%  -3%
paul 95057/s   1%   --  -2%
greg 96678/s   3%   2%   --

Greg's is marginally faster.  But it is arguably the more correct of the three 
implementations (if you run the test on my box with this limited data set).

Paul



More information about the PLUG mailing list