That is correct, but its not as obvoious as you may think.
Among other things, realize that the space may be continous for array bodies or may not. Also, as the hash keys are stored in a separate table, it depends on how long is the key, and of course, the length of the value for both hashes and arrays.
Some examples:
use Devel::Size qw(size);
my @array;
my %hash;
my $array_size = size(\@array);
my $hash_size = size(\%hash);
print "Array: $array_size, Hash: $hash_size\n";
The hash allocates more memory in this case, and allocates more than the array in a lineal comparison for every filled key-value pair in the hash, and any contiguous index-value in the array.
On the other hand, you can try this:
use Devel::Size qw(size);
use Data::Dumper;
my @array;
my %hash;
$hash{'f'} = 140;
$array[141] = 142;
print Dumper @array;
my $array_size = size(\@array);
my $hash_size = size(\%hash);
print "Array: $array_size, Hash: $hash_size\n";
Array indexes 0..141 are undefined, but some memory is reserved. In this case, for a single value a hash takes few memory.
| [reply] [d/l] [select] |
How come I lose reputation for a reply?
Walking the road to enlightenment... I found a penguin and a camel on the way.....
Fancy a yourname@perl.me.uk? Just ask!!!
| [reply] |
Downvoting isn't deterministic, each one has its own sensibility and culture.
In this particular case, I did not downvote your reply but I was a bit upset for your response. If you already knew some fields of interest in the differences between arrays and hashes, you could tell them in your original question, without waiting for responses and marking them as "ok, this is what I expected".
Moreover, your original post sounds like "I don't know when I should use one or another", so you got lots of replies pointing you to the basic documentation (and they were kind not to tell you RTFM). On the contrary, your reply springs up an interest into spatial efficiency, which is not a "newbie" issue, but a deeper one - this, I think, contributed to upset some monks.
Anyway, XP is just a number :)
Flavio
Don't fool yourself.
| [reply] |
Uses less space than a hash (I think)
Unless you're using e.g. phone-numbers as the index: see the sparse array point above. "Uses less space per value than an array" would be better but kind of obvious - Perl has to store the key as well. | [reply] |