Skip to content

Instantly share code, notes, and snippets.

@notbenh
Created June 4, 2015 18:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save notbenh/3c60b3127835f84d951e to your computer and use it in GitHub Desktop.
Save notbenh/3c60b3127835f84d951e to your computer and use it in GitHub Desktop.
checking to see if a single map is any faster than multiple with a grep? how does that compare with a foreach?
#!/usr/bin/env perl
use strict;
use warnings;
use Test::More;
use Benchmark qw{:all};
my @input = 1..9999;
sub map_and_grep { map{$_ * 2} grep{ m/9/ } map{$_ / 2} @_ };
sub single_map { map{ my $v = $_ / 2; $v =~ m/9/ ? $v * 2 : () } @_ }
sub for_each {
my @output;
for (@_){
my $v = $_ / 2;
push @output, $v * 2
if $v =~ m/9/;
}
@output;
}
is_deeply [ map_and_grep(@input)],
[ single_map(@input)],
q{output is the same between maps};
is_deeply [ map_and_grep(@input)],
[ for_each(@input)],
q{output is the same for the for loop};
cmpthese( 999, {
map_and_grep => sub{ map_and_grep(@input)},
single_map => sub{ single_map(@input)},
for_each => sub{ for_each(@input)},
});
done_testing;
@notbenh
Copy link
Author

notbenh commented Jun 4, 2015

ok 1 - output is the same between maps
ok 2 - output is the same for the for loop
               Rate map_and_grep     for_each   single_map
map_and_grep 99.2/s           --         -23%         -25%
for_each      129/s          30%           --          -3%
single_map    133/s          34%           3%           --
1..2
perl ./mass_map.t  25.50s user 0.04s system 99% cpu 25.582 total

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment