in reply to Performance issues with subroutines/methods
As others have identified, there is a fairly high, fixed overhead for calling subroutines (and therefore methods) in Perl (or any dynamic language). Beyond moving to a compiled language, there are only two things you can do.
The overhead is fixed. It's effect on performance is most pronounced when the body of the subroutine does very little. Adding a little 'do nothing, but expensively' code to your benchmark:
sub add { ## Other subs modified in the same way. my $temp = $_[0] ** int( 1/ $_[ 1 ] ); return $_[0] + $_[1]; }
Results:
## original C:\test>junk Rate Method^2 Method Method^3 Sub Sub^2 Method^2 720070/s -- -4% -12% -28% -32% Method 747754/s 4% -- -9% -25% -30% Method^3 820126/s 14% 10% -- -18% -23% Sub 998208/s 39% 33% 22% -- -6% Sub^2 1063462/s 48% 42% 30% 7% -- ## Modified C:\test>junk Rate Method Method^3 Method^2 Sub Sub^2 Method 488925/s -- -2% -2% -14% -23% Method^3 497153/s 2% -- -1% -13% -22% Method^2 500096/s 2% 1% -- -12% -21% Sub 569519/s 16% 15% 14% -- -10% Sub^2 635516/s 30% 28% 27% 12% --
Once the subs do more, the apparent cost of the calls is reduced.
Of course, that flies in the face of OO doctrine that suggests that methods should be short.
The costs are especially high if you choose to avoid direct access to your instance data and wrap all accesses in getter/setter subs.
You can further exacerbate the costs, by using one of the many 'safe' object implementations that add another level or two of indirection to the object and method resolution chains. All the 'inside out object' implementations fall into this category.
If you use one of the canned parameter validation mechanisms that use tied variables as a part of their implementation, you compound the costs again.
If you operate in an environment that is IO bound, or where performance is not an issue, these techniques are very effective and useful. But in a cpu-bound, performance constrained environment, you have to take the decision as to which is the higher priority.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Performance issues with subroutines/methods
by fenLisesi (Priest) on Jun 19, 2007 at 06:56 UTC | |
by BrowserUk (Patriarch) on Jun 19, 2007 at 07:15 UTC |