kiat has asked for the wisdom of the Perl Monks concerning the following question:

Hi monks,

If you have a somewhat large hash to store, is a normal hash a better solution or an annoymous hash? That is

my %hash = ( one => "it's a one", two => "it's a two", ); my $hashref = { one => "it's a one", two => "it's a two", };
Any difference in speed or performance? Or is it just a matter of preference?

Hope to hear from you soon and thanks in anticipation :)

Replies are listed 'Best First'.
Re: Anonymous or normal hashes?
by liz (Monsignor) on Jan 09, 2004 at 14:40 UTC
    There is no difference between a "hash reference" and a "hash" in terms of performance. In simple terms, internally a "hash" is just a "name" (global or lexical) with a "hash reference" attached to it internally.

    And you don't need a hash reference to pass hashes quickly to subroutines: you can generate references to hashes "on the fly":

    foo( \%hash ); # hashref created "on the fly" by taking ref of hash foo( $hashref ); # use hash reference stored in a scalar
    Both become the same type of hash reference inside  sub foo.

    Hope this helps.

    Liz

      There is going to be a very slight time difference between $hash{foo} and $hashref->{foo}, since the latter takes one additional operation (assuming both are lexicals). But any difference is likely to be trivial enough that it should be a matter of preference.
Re: Anonymous or normal hashes?
by Abigail-II (Bishop) on Jan 09, 2004 at 14:47 UTC
    It hardly matters. The hashref actually takes more memory, as you have the overhead of the reference itself. But that's about 12 bytes (or 16 if you have 64 bit pointers) per hash.

    Abigail

Re: Anonymous or normal hashes?
by borisz (Canon) on Jan 09, 2004 at 14:21 UTC
    in your example is no difference, the big difference is if you pass the hashes around ie:
    my_sub(%hash); # slow for big hashes my_other_sub($hashref); # fast
    Boris
      But that has nothing to do with anonymous vs. non-anonymous hashes.
      my_sub (%{ ... }) # Slow for big anonymous hashes. my_other_sub (\%hash) # Fast for non-anonymous hashes.

      Abigail

        I'm curious. How about situation where you have prototyped a subroutine eq. sub my_add (\%@) {} what then requires a % in call instead or \% of $hash_ref? Does that change the speed of the call?
        But that has nothing to do with anonymous vs. non-anonymous hashes.
        Yes, as I wrote. There is no difference in your example.
        Boris