in reply to Optimizing non-alphanumeric method calls

Is this an option?

my $can = $obj->can('method'); cmpthese(-1, { direct => sub { $obj->method }, can2 => sub { $can->($obj) }, } ); __END__ Rate direct can2 direct 15259941/s -- -21% can2 19276812/s 26% --

Replies are listed 'Best First'.
Re^2: Optimizing non-alphanumeric method calls
by trizen (Hermit) on Sep 27, 2015 at 18:46 UTC

    It could be in some places, but not in all of them, such as when a method is called on the result returned by an expression.

    Thanks though, I will consider this a special optimization.

      Should be noted that it's equivalent to writing $obj->$can() (what I called $c_method )

      Benchmarks shouldn't change.

      update

      I think a 3% penalty is an affordable prize for clarity and easier chaining. (actually it's ignorable, Benchmark isn't that exact)

      $ perl use Benchmark qw(cmpthese); package Example { sub new { bless {}, __PACKAGE__ } sub method { } } my $obj = Example->new; my $meth = 'method'; my $can = $obj->can('method'); cmpthese(-1, { direct => sub { $obj->method }, can2 => sub { $can->($obj) }, can3 => sub { $obj->$can() }, } ); __END__ Rate direct can3 can2 direct 893673/s -- -24% -26% can3 1180322/s 32% -- -3% can2 1214700/s 36% 3% --

      Cheers Rolf
      (addicted to the Perl Programming Language and ☆☆☆☆ :)
      Je suis Charlie!