If perl wouldn't fill in the "buckets", then the buckets would contain random garbage. Since perl reuses memory, that garbage may well be old array elements. How would perl know which array elements are "valid" and which ones are "not filled in"?
Note that (internal, C-level) arrays contain pointers to SVs. | [reply] |
| [reply] |
my @array;
$array[1000] = 1;
you still need to allocate space for 1001 pointers. Initialized or not.
I just tried it. Setting element 10000 of an array takes 0.35 MB more RAM than setting element 0 on perl 5.8.8 for OS X on Intel. So, there's a cost, although not a large one.
That's about 36 bytes/element. More that I expected. An undefined value takes 20 bytes in Perl. A pointer takes 4 bytes (32-bit platform). So, even if undefined values aren't shared, I'd expect less.
However, I cannot recreate this:
$ perl -MDevel::Size=:all -wE '$a[1] = 1; say total_size \@a'
148
$ perl -MDevel::Size=:all -wE '$a[10000] = 1; say total_size
\@a'
40136
which is a difference of about 40000 bytes, aka 10000 pointers. Replacing Devel::total_size with <c>`grep VmRSS /proc/$$/status` confirms the difference of 40000 bytes. | [reply] [d/l] [select] |