public
Created

Check if method is defined before assigning to it and benchmark #perl

  • Download Gist
assignment_vs_check_first.pl
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
use 5.014;
use Benchmark 'cmpthese';
 
my @ATTRIBUTES = qw( foo bar foo baz foo );
 
cmpthese(
-10,
{ assignment => sub {
package Assignment;
for my $attribute (@ATTRIBUTES) {
no strict 'refs';
*{$attribute} = sub {$attribute};
}
},
check_first => sub {
package CheckFirst;
for my $attribute (@ATTRIBUTES) {
next if __PACKAGE__->can($attribute);
no strict 'refs';
*{$attribute} = sub {$attribute};
}
},
}
);
 
# Rate assignment check_first
# assignment 253760/s -- -59%
# check_first 617345/s 143% --
edit_symbol_table.t
Perl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
use 5.014;
use Test::Most;
use List::MoreUtils 'uniq';
 
note 'check if the attribute exists in symbol table befor adding';
{
my @methods = qw( foo bar foo baz foo );
my $update_count = 0;
 
for my $method (@methods) {
next if __PACKAGE__->can($method);
no strict 'refs';
*{$method} = sub {$method} and $update_count++;
}
 
is $update_count, 3, 'symbol table updated 3 times';
can_ok __PACKAGE__, uniq @methods;
}
 
done_testing;

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.