Greets,

I was running some benchmarks to see how much of a penalty you incur when calling a sub as a method as opposed to a function, and I came across something unexpected: prepending a function name with an ampersand makes the call faster.

I suppose this is because the ampersand identifies the token as a function name, and so Perl doesn't have to spend any time disambiguating it -- but I'm surprised that that seems to be happening on the fly, at run-time.

Guess I'll be lubricating a few bottlenecks with ampersands...

#!/usr/bin/perl # sub_speed.plx -- compare speed for calling sub package Foo; sub do_nothing { } package main; use strict; use warnings; use Benchmark qw( cmpthese ); my $foo = bless {}, 'Foo'; sub do_nothing { } cmpthese( -1, { k1 => sub { $foo->do_nothing }, k2 => sub { Foo->do_nothing }, k3 => sub { Foo::do_nothing }, k4 => sub { do_nothing }, k5 => sub { &do_nothing }, });

k2 1456626/s -- -17% -34% -36% -47% k1 1745245/s 20% -- -21% -23% -36% k4 2210645/s 52% 27% -- -3% -19% k3 2277634/s 56% 31% 3% -- -16% k5 2723258/s 87% 56% 23% 20% --
--
Marvin Humphrey
Rectangular Research ― http://www.rectangular.com

In reply to Ampersands and sub speed by creamygoodness

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.