Created
September 19, 2012 12:22
-
-
Save kimmel/3749364 to your computer and use it in GitHub Desktop.
A Perl benchmark of foreach loops
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/perl | |
use v5.16; | |
use warnings; | |
use autodie qw( :all ); | |
use utf8::all; | |
use List::MoreUtils qw( uniq any ); | |
use Benchmark qw( cmpthese :hireswallclock ); | |
my %file_names = (); | |
my $fname = 'dt'; | |
my $pattern_list = do 'from_wp.pl.dict'; | |
my @words = ( | |
'the', 'this', 'that', 'candy', | |
'steak', 'frown', 'moose', 'bubba', | |
'alter', 'cow', 'house', 'doctor', | |
'who', 'return', 'jester', 'numerous', | |
'erase', 'vodka', 'beer', 'weeds', | |
'flowers', 'paste', 'round', 'taxi', | |
'car', 'impossible', 'programmer', 'cat', | |
'chicken', | |
); | |
cmpthese( | |
#5000, | |
-7, | |
{ 'method1' => sub { | |
foreach my $word (@words) { | |
my $key = lc substr $word, 0, 1; | |
$file_names{$fname}->{$word} = 1 | |
if ( | |
grep { $word eq $_ } | |
keys %{ $pattern_list->{$key} } | |
); | |
} | |
}, | |
'method2' => sub { | |
foreach my $word (@words) { | |
my $key = lc substr $word, 0, 1; | |
my @finds | |
= grep { $word eq $_ } keys %{ $pattern_list->{$key} }; | |
if (@finds) { | |
$file_names{$fname}->{$word} = 1; | |
} | |
} | |
}, | |
'method3' => sub { | |
foreach my $word (@words) { | |
my $key = lc substr $word, 0, 1; | |
if ( any { $word eq $_ } keys %{ $pattern_list->{$key} } ) { | |
$file_names{$fname}->{$word} = 1; | |
} | |
} | |
}, | |
'method4' => sub { | |
foreach my $word (@words) { | |
my $key = lc substr $word, 0, 1; | |
my @patterns = keys %{ $pattern_list->{$key} }; | |
if ( any { $word eq $_ } @patterns ) { | |
$file_names{$fname}->{$word} = 1; | |
} | |
} | |
}, | |
'method5' => sub { | |
foreach my $word (@words) { | |
my @patterns | |
= keys %{ $pattern_list->{ lc substr $word, 0, 1 } }; | |
if ( any { $word eq $_ } @patterns ) { | |
$file_names{$fname}->{$word} = 1; | |
} | |
} | |
}, | |
} | |
); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment