Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chriss Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

optimising perl hash appends

Status
Not open for further replies.

columb

IS-IT--Management
Joined
Feb 5, 2004
Messages
1,231
Location
EU
I have a subroutine which returns a reference to a hash. Trimming out the excess the code looks like
Code:
my %fullhash;
foreach my $val ( @arr )
  {
  my $hashref = dosubroutine ( $val );
  %fullhash = ( %fullhash, %$hashref );
  }
However, I'm concerned that each time the line
Code:
%fullhash = ( %fullhash, %$hashref );
is run perl will need to effectively recreate %fullhash, which I expect to grow quite large. As an inexperienced perl coder this looks inefficient.

As an alterntive I'm looking at
Code:
my %fullhash;
foreach my $val ( @arr )
  {
  my $hashref = dosubroutine ( $val );
  foreach ( keys %$hashref )
    { $fullhash{$_} = $hashref->{$_}; }
  }
As my test data is much smaller than the live data at the moment I can't do any direct timings. I would welcome any comments on which way to go.

Thanks

Ceci n'est pas une signature
Columb Healy
 
I believe the second method is more efficient. But if there is a large amount of data the array (@arr) could consume a lot of system memory it self. You should maybe do something like:

Code:
my %fullhash;
foreach my $val ( @arr )
  {
  my $hashref = dosubroutine ( $val );
  foreach ( keys %$hashref )
    { $fullhash{$_} = $hashref->{$_}; }
  }
[b]@arr = ();[/b]

to free up the memory.

- Kevin, perl coder unexceptional!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top