Håkon Hægland
Håkon Hægland

Reputation: 40778

Why is the refcount for a sub higher than for an array?

I have this test program:

use strict;
use warnings;
use Devel::Refcount qw( refcount );
my $subref = sub {1};
printf "\$subref has REFCNT=%d\n", refcount( $subref );
my $arrayref = [];
printf "\$arrayref has REFCNT=%d\n", refcount( $arrayref );

Output:

$subref has REFCNT=2
$arrayref has REFCNT=1

Why is the reference count for the sub 2 (I expected it to be 1 as for the array ref)?

Upvotes: 0

Views: 41

Answers (1)

Dave Mitchell
Dave Mitchell

Reputation: 2403

In the case where a closure isn't involved (i.e. the sub doesn't refer to any outer lexical variables), perl optimises things by sharing the sub (CV) rather than cloning it. So the first ref is for the "prototype" sub created at compile time, with an additional ref for each $subref created at runtime (an RV pointing at the original CV).

Upvotes: 4

Related Questions