Greetings honorable Monks,

I am doing some massive data processing, and in my quest for additional speed I wrote the following to check how well does perl actually perform:
use Benchmark qw(:all); my $a = 10; my $b = 20; cmpthese(-2, { 'Direct' => sub { my $c = $a+$b; }, 'Sub' => sub { my $c = add ($a, $b); }, 'Method' => sub { my $c = __PACKAGE__->meth_add ($a, $b); }, 'Method+sub' => sub { my $c = __PACKAGE__->meth_sub_add ($a, $b); }, 'Sub^2' => sub { my $c = add2 ($a, $b); }, 'Method^2' => sub { my $c = __PACKAGE__->meth2 ($a, $b); }, }); sub add { return $_[0] + $_[1]; } sub add2 { return add (@_); } sub meth_add { shift; return $_[0] + $_[1]; } sub meth_sub_add { shift; return add (@_); } sub meth2 { return $_[0] -> meth_add ( $_[1], $_[2] ); }
And here are the results I get:
                Rate Method^2 Method+sub     Sub^2    Method       Sub    Direct
Method^2    500713/s       --       -22%      -37%      -44%      -58%      -91%
Method+sub  643967/s      29%         --      -19%      -27%      -46%      -88%
Sub^2       797484/s      59%        24%        --      -10%      -33%      -85%
Method      886331/s      77%        38%       11%        --      -26%      -84%
Sub        1191561/s     138%        85%       49%       34%        --      -78%
Direct     5397078/s     978%       738%      577%      509%      353%        --
Now I understand how method dispatch works and why it is slow, but I do not understand why subroutines suffer almost the same penalty. Is there some kind of perl compile flag, or some hidden optimization that can improve these numbers (which _really_ add up in a complex code flow)?

Thanks

Peter

In reply to Performance issues with subroutines/methods by ribasushi

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.