There is only one reason to not use your own accessor methods, and that's to microoptimize your code for speed.Just to see the speed difference between direct vs. method access, I did a little benchmark. If speed is important and you are using accessors repeatedly in a tight loop, there certainly is merit to direct access.
use strict; use Benchmark "cmpthese"; my $foo = new foo; cmpthese(-5,{ direct=>sub{ $foo->{bar} }, accessor=>sub{ $foo->bar; } } ); package foo; sub new { my $class = shift; my $self = { bar=>"I am a bar" }; bless $self,$class; } sub bar{ my $self = shift; if (@_) { return $self->{bar} = shift; } return $self->{bar}; } __OUTPUT__ Benchmark: running accessor, direct, each for at least 5 CPU seconds.. +. accessor: 6 wallclock secs ( 5.08 usr + 0.01 sys = 5.09 CPU) @ 99 +4059.72/s (n=5059764) direct: 4 wallclock secs ( 5.07 usr + -0.01 sys = 5.06 CPU) @ 67 +95643.87/s (n=34385958) Rate accessor direct accessor 994060/s -- -85% direct 6795644/s 584% --
In reply to Re: Make your classes use their own methods
by fletcher_the_dog
in thread Make your classes use their own methods
by petdance
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |