Reputation: 23275
for $i (1..1000000)
{
my $a = rand(10);
my $b = rand(10);
my $c = rand(10);
}
Will the above code allocate new memory locations for $a
, $b
and $c
during each iteration of the loop, thereby using up more memory than the following code?
my ($a,$b,$c);
for $i (1..1000000)
{
$a = rand(10);
$b = rand(10);
$c = rand(10);
}
Upvotes: 2
Views: 88
Reputation: 85767
(First off, $i
shouldn't be a global variable, so that should be for my $i (...)
. Second, don't use the names $a
and $b
, not even in examples, because they're special variables used by sort
.)
The naive answer to that question is no, because $a
, $b
, and $c
are freed when reaching the end of the block }
, so the net result of an iteration is zero change in memory use.
The actual implementation in perl is even smarter: It reuses the memory for $a
/$b
/$c
so it doesn't have to repeatedly free and then reallocate the same piece of memory. (Of course, it can't do that if you create a reference to one of the local variables that persists beyond the loop body, because then the variable stays alive even though its name has gone out of scope.)
You can confirm that is the case by changing the loop to this:
for my $i (1 .. 5) {
my $x = rand 10;
my $y = rand 10;
my $z = rand 10;
print join(" ", \$x, \$y, \$z), "\n";
}
The output will be something like
SCALAR(0x4a5788) SCALAR(0x4a5728) SCALAR(0x4a56c8)
SCALAR(0x4a5788) SCALAR(0x4a5728) SCALAR(0x4a56c8)
SCALAR(0x4a5788) SCALAR(0x4a5728) SCALAR(0x4a56c8)
SCALAR(0x4a5788) SCALAR(0x4a5728) SCALAR(0x4a56c8)
SCALAR(0x4a5788) SCALAR(0x4a5728) SCALAR(0x4a56c8)
which demonstrates that the memory locations are identical in all loop iterations.
Upvotes: 5