bliako has asked for the wisdom of the Perl Monks concerning the following question:

Hello lockdown ones,

Everytime I declare a variable I believe a flop dies in my CPU. Probably because I fell in the C cauldron in my formative years. But now, and in Perl, the paradigm is to "lexicalise" variables within the innermost scope. For example, for:

my $x; for $x (1,2,3){ print "x=$x\n" }

perlcritic a.pl says Loop iterator is not lexical at line 6, column 1.  See page 108 of PBP.  (Severity: 5)

But this pacifies perlcritic:

for my $x (1,2,3){ print "x=$x\n" }

But wakes in me primordial fears of will that variable be created 3 times and decrease performance? (for the sake of readability and, perhaps, stability and not introducing subtle bugs). Does anyone know the difference in performance between the two scripts? Even if it is tiny!

bw, bliako

Replies are listed 'Best First'.
Re: declaring lexical variables in shortest scope: performance?
by tobyink (Canon) on Mar 31, 2020 at 10:54 UTC

    As well as what others have said, remember that Perl does have optimizations in place for common idioms. For example

    my @things = ( ... ); # some list, whatever @things = sort @things;

    You may think that sort gets passed @things, then returns the sorted list of things, and that gets assigned back to the @things array as a list assignment. But you'd be wrong. Perl notices that you're sorting an array and assigning it back to itself, and uses an optimized code path that doesn't involve having to build a new list and do list assignment; it does an in-place sort.

    Common idioms do get optimized for when possible, so there are benefits to sticking with them.

    With for my $var (...) {...}, Perl knows that $var won't be leaking outside the body of the loop, so can at least potentially optimize based on that.

Re: declaring lexical variables in shortest scope: performance?
by haukex (Archbishop) on Mar 31, 2020 at 10:38 UTC

    At least on my 5.28, the difference is negligible:

    use warnings; use strict; use Benchmark 'cmpthese'; cmpthese(-2, { predecl => sub { my $y; my $x; for $x (1,2,3) { $y+=$x } }, lexical => sub { my $y; for my $x (1,2,3) { $y+=$x } }, }); __END__ Rate predecl lexical predecl 9175035/s -- -1% lexical 9275893/s 1% --
    But wakes in me primordial fears

    Yes, I know the feeling well. But my philosophy has become: first, code so that it works, avoiding only the really obvious performance mistakes (like scanning an array instead of using a hash and the like). Then, if it's fast enough for your puproses, you're done. But if you want to optimize, remember that optimization is a science: measure the performance, identify the hotspots, benchmark the alternatives, modify the code accordingly, measure the difference in performance, and repeat until the performance becomes good enough for your purposes.

      Thanks for the compare script. Indeed the lexical is a bit faster (probably what tobyink said about internal optimisations) and is confirmed by choroba but when I declare a lexical variable inside the loop for my $x (1,2,3) {my $z=12; $y+=$x } in predecl, it's 50% slower :(

      I keep what you said about optimisation is a science

        > it's 50% slower

        Do you mean you added the my $z=12; to both the subroutines and the lexical one became 50% slower? I can't reproduce that behaviour. Adding it to only one of the subs slows it (35% in my case), but then we are comparing apples and oranges.

        map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      Maybe it is negligible but that is Benchmark pitfall, overhead drowns out what you're measuring, in line sub contents as strings not sub calls
        overhead drowns out what you're measuring, in line sub contents as strings not sub calls

        Can you show the code that demonstrates this?

Re: declaring lexical variables in shortest scope: performance?
by choroba (Cardinal) on Mar 31, 2020 at 10:40 UTC
    As usually, when you are interested in performance, benchmark or profile.
    #! /usr/bin/perl use warnings; use strict; use Benchmark qw{ cmpthese }; sub outer { my $s = 0; my $x; for $x (1 .. 5) { $s += $x; } $s } sub inner { my $s = 0; for my $x (1 .. 5) { $s += $x; } $s } outer() == inner() or die 'Error in implementation'; cmpthese(-2, { outer => 'outer()', inner => 'inner()', });

    The result on my machine shows inner is about 6% faster. Such a small difference is insignificant and usually has no real impact on real performance.

    Why is that? Remember that for localises its variable when it's not lexical, i.e. it has to store its previous value before entering the loop and restore it at the loop's end. It seems to take a bit more time than just creating a fresh new lexical variable.

    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]
      Benchmark pitfall, overhead drowns out what you're measuring, in line sub contents as strings not sub calls

        I didn't know that! Is the logic behind replacing the sub with a string expression, to fool the cache?

        use Benchmark 'cmpthese'; cmpthese(-2, { predecl => ' my $y; my $x; for $x (1..10000) { $y+=$x } ', lexical => ' my $y; for my $x (1..10000) { $y+=$x } ', }); __END__
        Rate lexical predecl lexical 3996/s -- -0% predecl 4001/s 0% --

        vs

        use Benchmark 'cmpthese'; cmpthese(-2, { predecl => sub { my $y; my $x; for $x (1..10000) { $y+=$x } }, lexical => sub { my $y; for my $x (1..10000) { $y+=$x } }, });
        Rate predecl lexical predecl 4011/s -- -0% lexical 4015/s 0% --

        Which is more or less what haukex and choroba demonstrated.

Re: declaring lexical variables in shortest scope: performance?
by LanX (Saint) on Mar 31, 2020 at 11:38 UTC
    In general:

    • Declaration happens at compile time which should be neglectable.
    • Assignment should be the same. (Or even faster°)
    • The only overhead could be destruction or resetting at end of scope.

    Your example with a for loop is a bit unfortunate, because aliasing is complicating things considerably.

    Together with various optimizations performance gains or loses should be unpredictable, especially between different versions of Perl.

    So benchmark it, I don't think it's worth the effort.

    °) BTW, for many years it was commonplace that private variables are faster, not sure if accessing package variables has been optimized in the mean time. ...

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

Re: declaring lexical variables in shortest scope: performance?
by GrandFather (Saint) on Mar 31, 2020 at 20:51 UTC

    In C/C++ the equivalent outer/inner code would perform identically. The compiler allocates space for all the local variables that might be needed on the stack on entry to the sub, usually by effectively incrementing the stack pointer. The "overhead" to create space for the local variables is typically the execution time of one processor instruction on each entry to the sub.

    Optimising for fewest key strokes only makes sense transmitting to Pluto or beyond
Re: declaring lexical variables in shortest scope: performance? (on Code Optimization and Performance References)
by eyepopslikeamosquito (Archbishop) on Apr 01, 2020 at 07:56 UTC

      fine with all these but if there is a long loop, then every little flop counts.

Re: declaring lexical variables in shortest scope: performance?
by vr (Curate) on Mar 31, 2020 at 17:53 UTC

    Isn't it the case that lexical loop iterator doesn't create a "lexical pad"? If a block, which creates scope, can be written so it doesn't have to create a "pad", then it's surely faster, no?

    use strict; use warnings; use Benchmark 'cmpthese'; cmpthese -2, { 1 => sub { my ( $s, $x, $y ) = 0; # for ( 1 .. 1e6 ) { # doesn't matter, if written so for my $i ( 1 .. 1e6 ) { $x = rand; # suppose intermediate $y = rand; # variables are required $s += $x + $y; } $s }, 2 => sub { my ( $s, $i ) = 0; # for $i ( 1 .. 1e6 ) { # doesn't matter, neither for ( 1 .. 1e6 ) { my $x = rand; my $y = rand; $s += $x + $y; } $s }, }; __END__ Rate 2 1 2 6.69/s -- -42% 1 11.6/s 74% --
Re: declaring lexical variables in shortest scope: performance?
by dsheroh (Monsignor) on Apr 01, 2020 at 07:46 UTC
    Perl is not, never has been, and almost certainly never will be a "high performance" language. If you're really that concerned about saving every flop, your first move should not be to question where to put my, your first move should be to switch to a different language.

    As long as you avoid the big mistakes like using inefficient algorithms, optimizing for correct operation and readability is generally going to be more than sufficient. Micro-optimizing things like the placement of variable declarations is almost never worth the effort, regardless of language, because the time you spend doing the optimization will generally be many, many orders of magnitude larger than the handful of microseconds that will actually be saved by the code speedup.

A reply falls below the community's threshold of quality. You may see it by logging in.