Skip to content

Instantly share code, notes, and snippets.

@ology
Created July 25, 2023 18:22
Show Gist options
  • Save ology/4db691b4d467d858db96fed804a6d553 to your computer and use it in GitHub Desktop.
Save ology/4db691b4d467d858db96fed804a6d553 to your computer and use it in GitHub Desktop.
Perl map vs foreach
#!/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;
}
}
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