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% --
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|