Eric J. Roode (
[email protected]) wrote on MMMDCLXXIII September
MCMXCIII in <URL:// -----BEGIN PGP SIGNED MESSAGE-----
// Hash: SHA1
//
// //
// >
// > a)
// > for (1..20) {
// > my $mod = $_%3;
// > ...
// > }
// >
// > b)
// > my $mod;
// > for (1..20) {
// > $mod = $_%3;
// > ...
// > }
// >
// > Let's say we'll need $mod only inside of foreach, so both cases work as
// > desired but is one more preferred then the other?
//
// Case (a) limits the scope of $mod to the for loop block. In general, it
// is good practice to limit the scope of variables as narrowly as possible,
// since you're less likely to use its value by mistake later. Or, suppose
// you later add a variable $mod in an enclosing outer scope. With case
// (a), you don't have to worry about stomping on the new variable's value.
// With case (b), you have two variables at the same scope that can
// conflict.
//
// Case (a) creates a new lexical variable each time through the loop; this
// probably slows the loop down by some microseconds. That's almost
// certainly inconsequential.
Actually, for a small loop that you run many times, it may matter:
#!/usr/bin/perl
use strict;
use warnings;
use Benchmark qw /cmpthese/;
our $loop = 1000;
cmpthese -2 => {
inner => ' for (1 .. $::loop) {my $m = $_ % 3}',
outer => 'my $m; for (1 .. $::loop) { $m = $_ % 3}',
};
__END__
Benchmark: running inner, outer for at least 2 CPU seconds...
inner: 2 wallclock secs ( 2.04 usr + 0.00 sys = 2.04 CPU)
@ 1982.35/s (n=4044)
outer: 2 wallclock secs ( 2.11 usr + 0.00 sys = 2.11 CPU)
@ 2858.77/s (n=6032)
Rate inner outer
inner 1982/s -- -31%
outer 2859/s 44% --
Abigail