Premature optimization is the root of all evil.
Re 1:
I don't think the difference is big enough. Especialy since the loops were real tight in the benchmark. If you actually call a subroutine in the loop you get much closer results. If I relace the $foo++ by a call to sub doSomething { $_[0]++ } I get:use strict; use Benchmark; my $a_huge_value = 10000000; sub outside { my($foo); for (my $i = 0; $i < $a_huge_value; $i++) { $foo = $i + 1; $foo++; } } sub inside { for (my $i = 0; $i < $a_huge_value; $i++) { my $foo = $i + 1; $foo++; } } timethese 1, { inside => \&inside, outside => \&outside, }; __END__ Benchmark: timing 1 iterations of inside, outside... inside: 6 wallclock secs ( 5.99 usr + 0.00 sys = 5.99 CPU) @ 0 +.17/s (n=1) outside: 5 wallclock secs ( 4.95 usr + 0.01 sys = 4.96 CPU) @ 0 +.20/s (n=1)
Anyway if you really do care about this tiny difference I would suggest a slightly different syntax:Benchmark: timing 1 iterations of inside, outside... inside: 12 wallclock secs (10.95 usr + 0.00 sys = 10.95 CPU) @ 0 +.09/s (n=1) outside: 10 wallclock secs ( 9.49 usr + 0.02 sys = 9.51 CPU) @ 0 +.11/s (n=1)
This way the $foo is created just once, yet it's declared just for the loop. You should be aware though that under some circumstances it may make a huge difference whether the variable is declared outside or inside the loop. If you plan to keep a reference to the variable you do need to declare it inside the loop so that you do get a new variable in each iteration!sub inInit { for (my ($i, $foo) = (0, 0); $i < $a_huge_value; $i++) { $foo = $i + 1; $foo++; } }
Re 2: First, you do not have any localy scoped variables in your code. You have a few LEXICALY scoped ones. Anyway all you need to notice is that
is valid Perl. You do not need the declaration to be allowed to assign to a list of variables! So there is actually no difference between this and the first question.for ($i = 0; $i < $a_whole_lot; $i++) { ($key, $value) = returnsAnArray(); }
Jenda
Always code as if the guy who ends up maintaining your code
will be a violent psychopath who knows where you live.
-- Rick Osborne
Edit by castaway: Closed small tag in signature
In reply to Re: Two Questions on "my"
by Jenda
in thread Two Questions on "my"
by C_T
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |