Perl: Linear lookup vs. Dictionary lookup times
Results:
Linear lookup:
wallclock secs ( 5.55 usr + 0.00 sys = 5.55 CPU) @ 18018.02/s (n=100000)
Dictionary Lookup:
0 wallclock secs ( 0.03 usr + 0.00 sys = 0.03 CPU) @ 3333333.33/s (n=100000)
Code used
#!/usr/bin/perl
use Benchmark qw/cmpthese timethese timethis/;
$index = 0;
if (open(CFILE,"acrobase.txt")) # if (we can open the file)
{
while($cb = <CFILE>) # while(there are lines we can read)
{
my @components = split /,/, $cb,3;
if ($components[0] ne "#" and $components[0][0] ne '\n')
{
$acrodict{$components[0]} = $components[2];
$acroarray[$index] = $components[0];
$exparray[$index] = $components[2];
$index = $index + 1;
}
}
close(CFILE);
}
#print $acrodict{"MHZ"} . "\n";
#print $exparray[32] . "\n";
# here's a method to search linearly for $param:
sub linlookup
{
my $param = shift;
for ($i=0; $i<$index; $i++)
{
if ($param eq $acroarray[$i])
{
return($exparray[$i]);
}
}
return("not found");
};
# here's a method to use a hash (dictionary) to look up $param:
sub dictlookup
{
my $param = shift;
return($acrodict{$param});
};
$n = 100000;
print timethis($n,'linlookup("IRS")');
print timethis($n,'dictlookup("IRS")');