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% --
In reply to Ampersands and sub speed by creamygoodness
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |