Search code examples
perlhashreferencesubroutine

Is instantiating a hash in a function inefficient in perl?


Is there any difference in doing the following, efficiency, bad practice...?

(In a context of bigger hashes and sending them through many functions)

sub function {
  my ($self, $hash_ref) = @_;
  my %hash = %{$hash_ref};
  print $hash{$key};
  return;
}

Compared to:

sub function {
  my ($self, $hash_ref) = @_;
  print $hash_ref->{$key};
  return;
}

Solution

  • Let's say %$hash_ref contains N elements.

    The first snippet does the following in addition to what the second snippet does:

    • Creates N scalars. (Can involve multiple memory allocations each.)
    • Adds N*2 scalars to the stack. (Cheap.)
    • Creates a hash. (More memory allocations...)
    • Adds N elements to a hash. (More memory allocations...)

    The second snippet does the following in addition to what the first snippet does:

    • [Nothing. It's a complete subset of the first snippet]

    The first snippet is therefore far less efficient than the second. It also more complicated by virtue of having extra code. The complete lack of benefit and the numerous costs dictate that one should avoid the pattern used in the first snippet.