Anonymous subs are cheaper in terms of usage (invoking a named sub includes a round-trip to the symbol table) and memory.
Named subs:
use strict; use warnings; my $begin; BEGIN { chop( $begin = `ps -o vsz= $$` )} eval "sub F_$_ { my( \$a, \$b, \$c ) = \@_; my \$x = $_; return \$a * \$b - (\$x + \$c); }" for 1..1e4; END { chop( my $end = `ps -o vsz= $$` ); print "$end - $begin = ",$end - $begin, "\n"; } __END__ 60924 - 22228 = 38696
Anonymous subs:
use strict; use warnings; my $begin; BEGIN { chop( $begin = `ps -o vsz= $$` )} my @ary; $ary[$_] = eval "sub { my( \$a, \$b, \$c ) = \@_; my \$x = $_; return \$a * \$b - (\$x + \$c); }" for 1..1e4; END { chop( my $end = `ps -o vsz= $$` ); print "$end - $begin = ",$end - $begin, "\n"; } __END__ 53356 - 22228 = 31128
That makes ca. 3.1kB per anonsub, 3.9 per named sub. Slightly different numbers than BrowserUk's above, but also slightly different architecture and version of perl:
perl 5, version 14, subversion 2 (v5.14.2) built for x86_64-linux-gnu-thread-multi
update: The ca. 750 extra bytes for named subs may well be just the cost of allocating a GLOB for the subroutine in the symbol table, which comes wiith SCALAR, HASH, ARRAY, CODE and FILEHANDLE slots. Currently I don't recall whether they are autovivified as needed or allocated in one go.
In reply to Re: Memory efficiency, anonymous vs named's vs local subroutines
by shmem
in thread Memory efficiency, anonymous vs named's vs local subroutines
by thanos1983
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |