How is most efficient way to pre allocate some memory in Perl global array ?
firstly array max is 40 - 41 KB which might be pushed beyond it then
all is due to aim in efficient runtime and avoid many reallocation expense
thanks in advance
I'm assuming that you are referring to memory allocation by the operating system to the Perl process. Normally memory allocation is a very fast and efficient process. So that's nothing to even think about.
Your second big misunderstanding seems to be in how Perl uses memory. It never releases and reallocates memory from the OS. (Exception: a few scenarios on Windows)
Variables in Perl are dynamically allocated so they automatically grab or release space in Perl's memory pool as Perl sees fit. You aren't supposed to even think about this. It's very different from C. There are no language level pointers or buffers.
If you have a situation where you are doing a huge number of "allocations", in your parlance, you probably just need a better algorithm.
The one situation where it makes to preallocate anything is when you will be doing a huge number of small incremental extensions to a variable or data structure. In that case you can use these tricks. Remember, don't do this unless your alogrithm truly demands it. Memory management is an implementation detail, so you can't count on this on any given platform.
# Force Perl to allocate some OS memory
{ local $_ = "\0" x 2**30; }
# Preallocate some buffer space for a string variable
my $x = "\0" x 2**20;
$x = "";
foreach (0 .. 2**19) {
$x .= get_something();
}
# Pre-extend an array
my @x;
$#x = 2**20 - 1;
@name
by setting its$#name
, the index of the last element. So if you say$#name = 99;
then@name
is allocated a hundred elements. However, those elements-to-be, the scalars, themselves cannot be assigned before time of course so the gain is probably not possible to even detect. Try and measure so that you can drop that idea and worry about items that will matter :)