in reply to Re: OOP - Constant Vs. Subroutine ()
in thread OOP - Constant Vs. Subroutine
agreed -- who cares. this in no way, shape, or form will noticably affect any sort of perl code.
I just brought this topic up, because I wanted to understand exactly why the speed difference existed. all i really care for is being able to stash & access class variables. I find using subs/constants is much easier than using 'our' scoped package variables for stashing info -- its just a quick $self->name instead of inspecting the object and moving on from there
In any event, I did the following benchmark below to test the speed difference between the various options in writing & calling these methods
Results vary on each run, but fall into 2 general categories...
faster:
sub get() { 'a'; } use constant get_constant=> 'a';
slower:
and the code...sub get { 'a'; } sub get { return 'a'; } sub get() { return 'a'; }
package class; use strict; sub new { my ( $proto )= @_; my $class= ref($proto) || $proto; my $self= bless ( {} , $class ); return $self; } sub get_sub { 'a'; } sub get_sub_nullproto () { 'a'; } sub get_sub_return { return 'a'; } sub get_sub_return_nullproto () { return 'a'; } use constant get_constant=> 'a'; package main; use strict; use Benchmark qw[ cmpthese ]; my $object= class->new(); cmpthese -1, { get_sub => sub { my $a= $object->get_sub; }, get_sub__paren => sub { my $a= $object->get_sub(); }, get_sub_nullproto => sub { my $a= $object->get_sub_nullproto; }, get_sub_nullproto__paren => sub { my $a= $object->get_sub_nullprot +o(); }, get_sub_return => sub { my $a= $object->get_sub_return; }, get_sub_return__paren => sub { my $a= $object->get_sub_return(); } +, get_sub_return_nullproto => sub { my $a= $object->get_sub_return_n +ullproto; }, get_sub_return_nullproto__paren => sub { my $a= $object->get_sub_r +eturn_nullproto(); }, get_constant => sub { my $a= $object->get_constant; }, get_constant__paren => sub { my $a= $object->get_constant(); }, };
|
|---|