is there a way I can optimise this subroutine?
You'll need to describe what your subroutine does a whole lot more clearly before anyone will be able to offer any major algorithmic efficiency changes.
For example: "Using the 2 store variables to specify a unique location, I want to get the unique products to write the whole array for that record_entry to an outfile and count the number of unique, duplicated and total products"; how does having "a unique location" allow you to "get the unique products"?
In the mean time, there are some very obvious implementation efficiencies that you could make.
my %comboHashRef = %{$_[2]};
You should avoid doing that by accessing the referenced hash indirectly. Ie. Instead of:
my %comboHashRef = %{$_[2]}; ... foreach my $key (keys %comboHashRef){
Do:
my $comboHashRef = $_[2]; ... foreach my $key (keys %{ $comboHashRef } ){
Or even better, avoid the generation of a large list and do:
my $comboHashRef = $_[2]; ... while( my( $key, $value ) = each %{ $comboHashRef } ){
return %precords;
And what that does is:
Whereas, if your simply returned a reference to the hash you built internally, you avoid all that deconstruction and reconstruction.
By way of example of the difference this can make, here is a deceptively simple benchmark:
sub yourWay{ my %h = %{ $_[0] }; return %h; };; sub myWay{ my $ref = shift; return $ref };; %hash = ( 1 .. 1e6 );; cmpthese -5,{ a=>q[ my %h = yourWay( \%hash ); ], b=>q[ my $h = myWay( \%hash ); ] };; s/iter a b a 1.12 -- -100% b 1.03e-006 108368213% --
And yes, those two subroutines are functionally equivalent. And yes; that figure of 1 million times more efficient is real!
No, those changes won't speed up your subroutine a million times; but they are changes worth making.
Now, can you clarify your description of the processing your sub does with a concrete example or two? If you can, you might get some good responses that will make a real dent in your problem.
In reply to Re: Optimise Sub, make hash unique based on values in array
by BrowserUk
in thread Optimise Sub, make hash unique based on values in array
by anomilie
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |