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

I know there are overheads to calling subs, but did not think they were sufficiently large that inline code runs millions of times per second while code refs run at fewer than ten times per second.

Purely out of curiosity, are the process and overheads documented anywhere? I can think of things like setting up @_ and other bookkeeping processes, but perhaps there are other steps.

  • Comment on Re^3: Should multiplication by integer be avoided in favour of division for performance reasons? (benchmark pitfalls)

Replies are listed 'Best First'.
Re^4: Should multiplication by integer be avoided in favour of division for performance reasons? (benchmark pitfalls)
by tobyink (Canon) on Nov 29, 2019 at 08:19 UTC

    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.

      Thanks for the details. I did get some improvements a while ago with some Inline::C code by pushing the loops into the C part instead of just the loop bodies, but don't recall seeing differences like those reported higher in this thread.

      I'll have a peruse of the XS docs and Sub::Block.