in reply to array pre-allocation trick

You have a good idea. The details are tripping you up.

Your code on the first call:

  1. creates @array,
  2. allocates @array,
  3. returns destroying @array as it goes out of scope

On future calls it just creates @array and starts using it. So your tests should not show any advantage.

Move the "my @array;" outside of the function so that it survives from call to call:

{ my $initialized; my @array; sub example { unless ( $initialized) { $#array = $size_needed; $initialized++; } # fill the array } }
Update follows

As soon as I submitted the above I realize that may not be what you want. You may be making this way harder than you need to.

If you need a new @array on each call. Just preallocate it each time:

sub example { my @array; $#array = $size_needed; # fill array -- this is where you may save time }

Replies are listed 'Best First'.
Re: Re: array pre-allocation trick
by strat (Canon) on Oct 31, 2002 at 11:08 UTC
    As far as I know, memory-preallocation with arrays generally doesn't improve speed very much. But it often may reduce memory fragmentation...

    Best regards,
    perl -e "s>>*F>e=>y)\*martinF)stronat)=>print,print v8.8.8.32.11.32"