Perl Training Australia - listsearch.pl


#!/usr/bin/perl -w
use strict;
use Benchmark qw(:all);
use List::Util qw(first);

# A big, sorted list, with 10702 elements.
my @list = (1..10000, 'a'..'zz');

my @selection;
# push a bunch of random things that do exist onto the list
foreach ( 1 .. 100 ) {
	push @selection, $list[rand @list];
}

# and a bunch of things which don't (total length 152)
foreach ( 'aaa' ... 'abz') {
	push @selection, $_;
}


my %exists;
@exists{@list} = ();

print "Comparing different sorting options small list over large list\n";
cmpthese(0, {
	# Looking for @selection in @list with grep
	'grep' => sub {
		my $found;
		foreach my $find (@selection) {
			$found = grep { $_ eq $find } @list;
		}
	},
	# Looking for @selection in @list with first
	'first' => sub {
		my $found;
		foreach my $find (@selection) {
			$found = first { $_ eq $find } @list;
		}
	},
	# Looking for @selection in @list linearly (with foreach)
	'foreach' => sub {
		my $found;
		foreach my $find (@selection) {
			foreach (@list) {
				if($_ eq $find) {
					$found = 1;
					last;
				}
			}
		}
	},
	# Looking for @selection in a hash of @list
	'lb-hash' => sub {
		my $found;
		my %hash;

		# build hash
		@hash{@list} = ();

		foreach my $find (@selection) {
			$found = exists $hash{$find};
		}
	},
	# Looking for @list against a list of @selection (short circuiting)
	'w-hash' => sub {
		my %hash;
		@hash{@selection} = ();
		foreach my $find (@list) {
			delete $hash{$find};

			last unless keys %hash;
		}
	},
	# Looking for @selection in pre-built @exists
	'pre-built hash' => sub {
		my $found;
		foreach my $find (@selection) {
			$found = exists $exists{$find};
		}
	},
});

Valid XHTML 1.0 Valid CSS