in reply to What defines the choice of a Hash or an Array?
$ARRAY->[1][2] = 'bob';
$HASH->{1}{2} = 'bob';
As this table shows about the only thing you can use a HASH data type for directly is as an array.
| data type | ARRAY | HASH |
| array | X | X |
| list | X | |
| iterator | X | |
| stack | X | |
| queue | X |
So should you use and HASH or an ARRAY to store arrays? Accessing the ARRAY data type is only slightly faster than accessing the HASH data type, so I would recomend using HASH arrays except for rare cases were speed is vital. If you your arrays are more more 1 dimentional then the ARRAY data type really looses all of its advantage over the HASH data type, as it can no longer be used directly as a list.
Rate HASH ARRAY
HASH 54856/s -- -5%
ARRAY 57536/s 5% --
And of course every thing else is in an ARRAY (or a SCALAR).
use Benchmark qw (cmpthese); use constant { SEC => 0, MIN => 1, HOUR => 2, MDAY => 3, MON => 4, YEAR => 5, WDAY => 6, YDAY => 7, ISDST => 8, }; our $array = [ qw (sec min hour mday mon year wday yday isdst ) ]; our $hash = { qw (SEC sec MIN min HOUR hour MDAY mday MON mon YEAR year WDAY wday YDAY yday ISDST isdst ) }; sub array { my $a; $a |= $array->[SEC]; $a |= $array->[MIN]; $a |= $array->[HOUR]; $a |= $array->[MDAY]; $a |= $array->[MON]; $a |= $array->[YEAR]; $a |= $array->[WDAY]; $a |= $array->[YDAY]; $a |= $array->[ISDST]; $a; } sub hash { my $a; $a |= $hash->{'SEC'}; $a |= $hash->{'MIN'}; $a |= $hash->{'HOUR'}; $a |= $hash->{'MDAY'}; $a |= $hash->{'MON'}; $a |= $hash->{'YEAR'}; $a |= $hash->{'WDAY'}; $a |= $hash->{'YDAY'}; $a |= $hash->{'ISDST'}; $a; } cmpthese(-1, { 'ARRAY' => \&array, 'HASH' => \&hash, }); cmpthese(-1, { 'ARRAY' => sub { sort @$array }, 'HASH' => sub { sort values %$hash }, });
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: What defines the choice of a Hash or an Array?
by chromatic (Archbishop) on Apr 01, 2005 at 00:11 UTC | |
by Anonymous Monk on Apr 01, 2005 at 08:12 UTC |