Skip to content

Instantly share code, notes, and snippets.

@j1n3l0
Created July 10, 2012 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save j1n3l0/3083224 to your computer and use it in GitHub Desktop.
Save j1n3l0/3083224 to your computer and use it in GitHub Desktop.
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