Created
June 4, 2015 18:46
-
-
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?
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/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; |
Author
notbenh
commented
Jun 4, 2015
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment