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
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. | [reply] [d/l] [select] |
|
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:
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. | [reply] [d/l] |
by bliako (Abbot) on Mar 31, 2020 at 11:05 UTC | |
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 | [reply] [d/l] |
by choroba (Cardinal) on Mar 31, 2020 at 11:27 UTC | |
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]
| [reply] [d/l] [select] |
by bliako (Abbot) on Mar 31, 2020 at 11:58 UTC | |
by LanX (Saint) on Mar 31, 2020 at 12:00 UTC | |
| |
by Anonymous Monk on Mar 31, 2020 at 11:52 UTC | |
| [reply] |
by haukex (Archbishop) on Mar 31, 2020 at 12:08 UTC | |
overhead drowns out what you're measuring, in line sub contents as strings not sub calls Can you show the code that demonstrates this? | [reply] |
|
Re: declaring lexical variables in shortest scope: performance?
by choroba (Cardinal) on Mar 31, 2020 at 10:40 UTC | |
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]
| [reply] [d/l] [select] |
by Anonymous Monk on Mar 31, 2020 at 11:50 UTC | |
| [reply] |
by bliako (Abbot) on Mar 31, 2020 at 12:09 UTC | |
I didn't know that! Is the logic behind replacing the sub with a string expression, to fool the cache?
vs
| [reply] [d/l] [select] |
|
Re: declaring lexical variables in shortest scope: performance?
by LanX (Saint) on Mar 31, 2020 at 11:38 UTC | |
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 | [reply] |
|
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
| [reply] |
|
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 | |
A couple of related general guidelines from On Coding Standards and Code Reviews: On Interfaces and APIs cautions that library interfaces are very difficult to change once they become widely used - a fundamentally inefficient interface cannot be easily fixed later by optimizing. So it is not "premature optimization" to consider efficiency when designing public library interfaces. See Also
These experiences convinced me of don't assume measure and especially find a better algorithm! Perl Performance References
High Performance and Parallel Computing References
Extra Performance/Optimization References Added Later Bitwise Operations:
Benchmark:
Database v Large Hash:
Other:
From BrowserUk (2012-2015):
From anonymonk (2023-2024):
From mldvx4 (2025):
Two spookily similar nodes posted late 2021 (both requesting XS C code, both by new monks who won't show us their code):
Some old classics:
Other:
On CPAN:
Some external references:
Mathematical:
Memory:
Sorting:
Multi-threading:
Compiler switches/flags: I/O: PDL and Array Processing References RPerl References
See Also
Updated: Added Donald Knuth premature optimization quote and Alexandrescu/Sutter premature pessimization quotes and Rob Pike quotes. Mentioned efficiency of interfaces. Added more references. | [reply] [d/l] [select] |
by bliako (Abbot) on Apr 01, 2020 at 08:13 UTC | |
fine with all these but if there is a long loop, then every little flop counts. | [reply] |
|
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?
| [reply] [d/l] |
|
Re: declaring lexical variables in shortest scope: performance?
by dsheroh (Monsignor) on Apr 01, 2020 at 07:46 UTC | |
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. | [reply] [d/l] |
| A reply falls below the community's threshold of quality. You may see it by logging in. | |