Skip to content

@j1n3l0 /assignment_vs_check_first.pl
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Check if method is defined before assigning to it and benchmark #perl
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% --
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;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Something went wrong with that request. Please try again.