Optimize Perl
By Martin C. Brown2005-04-11
Loops
As you've already seen, function calls with arguments are expensive, because for the function call to work, Perl has to put the arguments onto the call stack, call the function, and then receive the responses back through the stack again. All of this requires overhead and processing that we could probably do without. For this reason, excessive function calls in a loop are generally a bad idea. Again, it comes down to a comparison of numbers. Looping through 1,000 items and passing information to a function will trigger the function call 1,000 times. To get around this, I just switch the sequence around. Instead of using the format in Listing 3, I use the approach in Listing 4.
Listing 3. Loop calling functions
Listing 4. Function using loops
foreach my $item (keys %{$values})
{
$values->{$item}->{result} = calculate($values->{$item});
}
sub calculate
{
my ($item) = @_;
return ($item->{adda}+$item->{addb});
}
Better still, in a simple calculation like this one or for any straightforward loop work, use map:
calculate_list($values);
sub calculate_list
{
my ($list) = @_;
foreach my $item (keys %{$values})
{
$values->{$item}->{result} = ($item->{adda}+$item->{addb});
}
}
map { $values->{$_}->{result} = $values->{$_}->{adda}+$values->{$_}->{addb} } keys %{$values};Remember also that each iteration through the loop wastes time, so rather than working through the same loop a number of times, try to perform all the actions in one pass through the loop.
Tutorial Pages:
» Squeeze the Most From Your Code
» Sloppy Programming, Sloppy Performance
» Approaching Optimization
» Use References
» String Handling
» Loops
» Sorts
» Using Short Circuit Logic
» Use AutoLoader
» Using Bytecode and the Compiler Back Ends
» Other Tools
» Putting it All Together
» Resources
First published by IBM DeveloperWorks
| Related Tutorials: » Random subroutines in Perl » Log Script Use » Creating Perl Modules for Web Sites » Bit Vector, Using Perl Vec » Build a Perl/CGI Voting System » Perl Range Operator |
