Hello dear Perl Monks,

I'm asking for help because I have a very delicate problem which involves objects and method calls. More specifically, it involves calling methods which have punctuation marks in their names, such as "+", "-", etc...

So far, I tried 5 different ways for making a method call, but all turned out to be much slower than specifying directly the method name (using Perl-5.22.0).

use Benchmark qw(cmpthese); package Example { sub new { bless {}, __PACKAGE__ } sub method { } } my $obj = Example->new; my $meth = 'method'; cmpthese(-1, { direct => sub { $obj->method }, var => sub { $obj->$meth }, ref => sub { $obj->${\'method'} }, can => sub { $obj->can('method')->($obj) }, magic => sub { ${ref($obj) . '::'}{'method'}->($obj) }, } );

(I used "method" for the method name just for illustration, but consider that "method" can have any possible name)

Output:

Rate magic can ref var direct magic 3495252/s -- -0% -37% -41% -58% can 3510857/s 0% -- -36% -40% -58% ref 5518821/s 58% 57% -- -6% -34% var 5887725/s 68% 68% 7% -- -29% direct 8340945/s 139% 138% 51% 42% --

(If you are wondering where do I need this; well, it's part of a toy-compiler which generates Perl code from a much higher language, in which any operation is translated into a method call)

My question now is, how can I make the Perl interpreter to optimize non-alphanumeric method calls, in the same way as it optimizes direct alphanumeric ones?

Thank you.


In reply to Optimizing non-alphanumeric method calls by trizen

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.