Skip to content

Instantly share code, notes, and snippets.

@petdance
Created December 15, 2022 14:55
Show Gist options
  • Save petdance/a696a4da79b9f42c30e840228245e31d to your computer and use it in GitHub Desktop.
Save petdance/a696a4da79b9f42c30e840228245e31d to your computer and use it in GitHub Desktop.
Optimizing sub recompilation
use 5.010;
use strict;
use warnings;
use Benchmark ':all';
my $COUNT = 10_000_000;
say "$COUNT iterations under $^V";
my %totals;
cmpthese( $COUNT, {
inline => sub {
runit( sub { ++$totals{inline} } );
},
my_sub => sub {
my $fn = sub { ++$totals{my_sub} };
runit($fn);
},
state_sub => sub {
state $fn = sub { ++$totals{state_sub} };
runit($fn);
},
} );
sub runit {
$_[0]->();
}
say "All counts in the hash should be $COUNT";
{use Data::Dumper; local $Data::Dumper::Sortkeys=1; say Dumper(\%totals)}
$ perl subs.pl
10000000 iterations under v5.20.3
Rate my_sub inline state_sub
my_sub 1340483/s -- -8% -63%
inline 1451379/s 8% -- -60%
state_sub 3623188/s 170% 150% --
All counts in the hash should be 10000000
$VAR1 = {
'inline' => 10000000,
'my_sub' => 10000000,
'state_sub' => 10000000
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment