-
-
Save ology/4db691b4d467d858db96fed804a6d553 to your computer and use it in GitHub Desktop.
Perl map vs foreach
This file contains 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 Benchmark; | |
my $count = shift || 100_000_000; | |
timethese($count, { | |
map_it => \&map_it, | |
for_it => \&for_it, | |
}); | |
sub map_it { | |
my @x = map { $_ ** 2 } 1 .. 100; | |
} | |
sub for_it { | |
my @x; | |
for (1 .. 100) { | |
push @x, $_ ** 2; | |
} | |
} |
This file contains 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
Benchmark: timing 100000000 iterations of for_it, map_it... | |
for_it: 895 wallclock secs (893.52 usr + 0.07 sys = 893.59 CPU) @ 111908.15/s (n=100000000) | |
map_it: 1118 wallclock secs (1117.01 usr + 0.05 sys = 1117.06 CPU) @ 89520.71/s (n=100000000) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment