Created
July 10, 2012 13:29
-
-
Save j1n3l0/3083224 to your computer and use it in GitHub Desktop.
Check if method is defined before assigning to it and benchmark #perl
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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% -- |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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