
Untitled
By: a guest on
May 10th, 2012 | syntax:
None | size: 2.34 KB | hits: 16 | expires: Never
use strict;
use warnings;
use Data::Dumper;
use List::Util qw/first shuffle/;
use Benchmark qw(timethese cmpthese);
use 5.10.0;
my $count = shift || 1;
my $dbg = ($count == 1) ? 1 : undef;
my $grep = 'apple';
my @array1 = ('a'..'z', 'A'..'Z', 'apple', 'mango', 'orange');
@array1 = shuffle(@array1);
my $comp = timethese(
$count,
{
list1 => sub {list1();},
list2 => sub {list2();},
list3 => sub {list3();},
list4 => sub {list4();},
list5 => sub {list5();},
}
);
warn Dumper (\@array1) if $dbg;
cmpthese $comp;
sub list1 {
foreach my $r (@array1) {
if($r eq $grep){
say "hit1!" if $dbg;
last;
}
}
}
sub list2 {
if(grep /^$grep$/, @array1){
say "hit2!" if $dbg;
};
}
sub list3 {
if(grep {$_ eq $grep} @array1){
say "hit3!" if $dbg;
};
}
sub list4 {
given ($grep) {
when (@array1) {
say "hit4!" if $dbg;
}
}
}
sub list5 {
if($grep ~~ \@array1){
say "hit5!" if $dbg;
};
}
__DATA__
% perl -v
This is perl 5, version 14, subversion 1 (v5.14.1) built for darwin-2level
Copyright 1987-2011, Larry Wall
Perl may be copied only under the terms of either the Artistic License or the
GNU General Public License, which may be found in the Perl 5 source kit.
Complete documentation for Perl, including FAQ lists, should be found on
this system using "man perl" or "perldoc perl". If you have access to the
Internet, point your browser at http://www.perl.org/, the Perl Home Page.
% perl list_grep.pl 300000
Benchmark: timing 300000 iterations of list1, list2, list3, list4, list5...
list1: 1 wallclock secs ( 0.71 usr + 0.01 sys = 0.72 CPU) @ 416666.67/s (n=300000)
list2: 5 wallclock secs ( 4.95 usr + 0.01 sys = 4.96 CPU) @ 60483.87/s (n=300000)
list3: 2 wallclock secs ( 1.91 usr + 0.00 sys = 1.91 CPU) @ 157068.06/s (n=300000)
list4: 1 wallclock secs ( 0.52 usr + 0.00 sys = 0.52 CPU) @ 576923.08/s (n=300000)
list5: 0 wallclock secs ( 0.45 usr + 0.00 sys = 0.45 CPU) @ 666666.67/s (n=300000)
Rate list2 list3 list1 list4 list5
list2 60484/s -- -61% -85% -90% -91%
list3 157068/s 160% -- -62% -73% -76%
list1 416667/s 589% 165% -- -28% -38%
list4 576923/s 854% 267% 38% -- -13%
list5 666667/s 1002% 324% 60% 16% --