[plug] Perl Question: Searching an array

Matthew Robinson matt at zensunni.org
Wed Feb 26 17:56:14 WST 2003


For anyone whose interested I've packaged up all of Tony's searching 
methods into a benchmark script, using the Benchmark module, to see 
which method is in fact the fastest.

The script searches the dictionary file (on my system it is 
/etc/alternatives/dictionary) for the string 'zoo'.  The script is as 
follows:

#!/usr/bin/perl

use strict;
use warnings;

use Benchmark;

my @list;
open(DICT, '/etc/alternatives/dictionary');
while(<DICT>) {
         chomp;
         push @list, $_;
}
close(DICT);

timethese(100, {
         for => sub {
                 for(my $i=0; $i <= $#list; $i++) {
                         if ($list[$i] eq 'zoo') {
                                 my $found = 1; 
        				last;
                         }
                 }
         },
         foreach => sub {
                 foreach my $word (@list) {
                         if ($word eq 'zoo') {
                                 my $found = 1;
                                 last;
                         }
                 }
         },
         grep => sub {
                 my $found = grep /zoo/, @list;
         },
         hash => sub {
                 my %list = map { ($_, 1) } @list;
                 my $found = 1 if ($list{zoo});
         },
});

__END__


This gives the following output:

Benchmark: timing 100 iterations of for, foreach, grep, hash...
for: 54 wallclock secs (26.73 usr +  0.02 sys = 26.75 CPU) @  3.74/s
foreach: 25 wallclock secs (12.40 usr +  0.00 sys = 12.40 CPU) @  8.06/s
grep: 15 wallclock secs ( 7.30 usr +  0.00 sys =  7.30 CPU) @ 13.70/s
hash: 104 wallclock secs (51.90 usr +  0.06 sys = 51.96 CPU) @  1.92/s


The output clearly shows that the grep function is the quickest followed 
by the foreach, for and finally hash methods.  Obviously, this test 
doesn't take into account the memory usage for each method.

Hope this helps,

Matt

-- 
print map{s&^(.)&\U\1&&&$_}split$,=$",(`$^Xdoc$,-qj`=~m&"(.*)"&)[0].$/



More information about the plug mailing list