in reply to Re^2: Why is "any" slow in this case?
in thread Why is "any" slow in this case?

My point was this:
use v5.40; my @subs; sub dosomething :prototype(&) { push @subs, $_[0]; } for (1..2) { my $x; dosomething { $x+1 } } for (1..2) { my $x; dosomething { $_+1 } } say for @subs
Output:
CODE(0x56271152c660) CODE(0x5627115470c8) CODE(0x5627115999e0) CODE(0x5627115999e0)

You can see by the addresses that Perl had to allocate a new coderef on each iteration of the first loop, but was able to reuse the coderef on the second loop.

Replies are listed 'Best First'.
Re^4: Why is "any" slow in this case?
by ikegami (Patriarch) on Aug 05, 2025 at 01:52 UTC

    In a dump, the closure has the CLONED flag. You can also see the capture.

    SV = IV(0x582c494d89d0) at 0x582c494d89e0 REFCNT = 1 FLAGS = (ROK) RV = 0x582c494b36b0 SV = PVCV(0x582c495314a8) at 0x582c494b36b0 REFCNT = 2 FLAGS = (ANON,CLONED,CVGV_RC,DYNFILE) COMP_STASH = 0x582c494b3530 "main" START = 0x582c494f9298 ===> 1 ROOT = 0x582c494f9220 GVGV::GV = 0x582c494eed80 "main" :: "__ANON__" FILE = "-" DEPTH = 0 FLAGS = 0x14c0 OUTSIDE_SEQ = 218 PADLIST = 0x582c494ca480 PADNAME = 0x582c494f87a0(0x582c494d5cc0) PAD = 0x582c494d8878(0x58 +2c494df290) 1. 0x582c494eeb88<2> FAKE "$x" flags=0x0 index=2 OUTSIDE = 0x0 (null)
Re^4: Why is "any" slow in this case?
by LanX (Saint) on Aug 04, 2025 at 21:28 UTC
    Yeah I see your point now.

    Seems like Perl is playing safe if a lexpad is required for the closure, even if the closed over lexical variable doesn't change, like here:

    $ perl use v5.14; my @subs; sub dosomething :prototype(&) { push @subs, $_[0]; } my $x; for (1..2) { dosomething { $x+1 } } for (1..2) { my $x; dosomething { $_+1 } } say for @subs; __END__ CODE(0x64405f0de700) CODE(0x64405f10b340) CODE(0x64405f118bb0) CODE(0x64405f118bb0)

    BTW: Clever move to push the code-refs to @subs and keeping them alive instead of printing them out.

    Like this you are avoiding that Perl tries to reuse a freed ref again! IOW if we see the same ref again we are sure teh sub wasn't generated again.

    Cheers Rolf
    (addicted to the Perl Programming Language :)
    see Wikisyntax for the Monastery