Re: Array Initialization



From: "John W. Krahn" <jwkrahn@xxxxxxx>
Bryan Harris wrote:

[stuff cut out]

It is usually best to declare variables in the smallest scope possible
so:

while (more work to do)
{
my @array = split $string;

# do work on array
}


Doesn't that try to re-localize (?) the @array variable every time
through the loop? i.e. doesn't it re-run the my() function every time
through the loop? For some reason I thought that was a no-no.

my() happens when the code is compiled so it is *not* re-run every time
through the loop. The assignment happens when the code is run so it is
re-run every time.

That's not entirely true. There is compiletime and runtime behaviour
of my(). It doesn't just silence 'use strict', it also allocates a
new variable. Each time you enter the loop body. See this:

for (1..10) {
my $x = 1;
print "The \$x is at " . \$x . "\n";
}
print "versus\n";
my @arr;
for (1..10) {
my $x = 1;
print "The \$x is at " . \$x . "\n";
push @arr, \$x;
}

As you can see in the first case it allocates the same memory, in the
second, because I remember the address, it has to allocate a new
chunk of memory every time.


OTOH, you should not care about this, the allocation is pretty quick,
especially if it can reallocate the same bit of memory every time.

Jenda
===== Jenda@xxxxxxxxxxx === http://Jenda.Krynicky.cz =====
When it comes to wine, women and song, wizards are allowed
to get drunk and croon as much as they like.
-- Terry Pratchett in Sourcery

.



Relevant Pages

  • Re: Memory Lifetime in Interop
    ... large value (so it allocates say a 128 Megabyte array), the memory allocated ... garbage collection when the function returns control to the client) and one ... From watching> the memory heap, if I set dynamic_value in the .NET code to be a rather> large value (so it allocates say a 128 Megabyte array), the memory> allocated ...
    (microsoft.public.dotnet.framework.interop)
  • Re: not enough storage... error using GetRows
    ... > array only contained ~150,000 rows. ... It took 19 minutes for GetRows to return (db ... and the prog had consumed 200MB of memory. ... The first one allocates some 180MB, the next two only allocate about 47MB ...
    (microsoft.public.vb.database.ado)
  • Re: Framework 2.0 array redim unsatisfactory performance
    ... I am not talking about "array redim" anymore. ... ReDim simply allocates a new ... but I do not even attempt to test its memory ...
    (microsoft.public.dotnet.languages.vb)
  • Re: Memory leak
    ... I have to give the program tens of megabytes of heap space or it ... During each loop of the method, I copy the contents of the array into ... amount of memory in usage does go up and down, ...
    (comp.lang.java.programmer)
  • Re: Hi Guys,CAN and PDA DAQ
    ... case of the case structure in your while loop, ... array function.  When you use the build array function like this ... This memory leak can affect system ...
    (comp.lang.labview)