When you call a sub, Perl needs to store the current @_ on the stack, along with data for caller in case that's called, needs to track call context (scalar, list, or void), plus the address of where to return to when the sub call has completed. Some of this can be avoided by using goto. Method calls are even more work because you need to look up at run time which sub to call, including traversing @ISA.

I'm pretty sure a lot of this is documented in Perl's XS documentation because calling a sub in XS is pretty manual and you have to do a lot of this yourself in C code. (Though there are macros to simplify it.)

Sub calls in Perl are one of the most time-expensive built-in operations that doesn't involve the filesystem or network.

In Type::Tiny, I go to ridiculous lengths to avoid sub calls. Like if you use a type constraint like ArrayRef[Int] you might think that there would be one sub to check that something is an arrayref, and then that would call the sub to check ints once for each element of the arrayref. But...

use Types::Standard qw( Int ArrayRef ); my $type = ArrayRef[ Int->where('$_ >= 0') ]; my $check = $type->compiled_check; # The following check is ONE sub call. Just one. if ($check->(\@somearray)) { ...; }

You might be interested in Sub::Block which automates some inlining stuff, especially with grep and map.


In reply to Re^4: Should multiplication by integer be avoided in favour of division for performance reasons? (benchmark pitfalls) by tobyink
in thread Should multiplication by integer be avoided in favour of division for performance reasons? by vr

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.