Skip to content
Create a gist now

Instantly share code, notes, and snippets.

Embed URL


Subversion checkout URL

You can clone with
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 );
{ 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;
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.